【问题标题】:UIImage vs NSImage: Drawing to an off screen image in iOSUIImage vs NSImage:在iOS中绘制到屏幕外图像
【发布时间】:2012-04-07 10:32:10
【问题描述】:

在 mac osx (cocoa) 中,很容易制作一个特定大小的空白图像并在屏幕外绘制:

NSImage* image = [[NSImage alloc] initWithSize:NSMakeSize(64,64)];
[image lockFocus];
/* drawing code here */
[image unlockFocus];

但是,在 iOS(可可触摸)中,似乎没有对 UIImage 的等效调用。我想使用 UIImage (或其他等效类)来做同样的事情。也就是说,我想制作一个明确大小的、最初为空的图像,我可以使用UIRectFill(...) 和[UIBezierPath stroke] 之类的调用来绘制它。

我该怎么做?

【问题讨论】:

    标签: objective-c cocoa-touch uiimage nsimage


    【解决方案1】:

    你可以这样做:

    UIGraphicsBeginImageContext(CGSizeMake(64, 64));
    //Drawing code here
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    这是 Apple 的 Graphics and Drawing 参考。

    【讨论】:

    • 但不要忘记结束图像上下文!
    • 好的,我假设这相当于创建NSImage 并调用lockFocus,但我将如何解锁焦点?
    • 使用函数UIGraphicsEndImageContext();。
    【解决方案2】:

    这里需要CoreGraphics,因为UIImage没有你解释的高级功能..

    UIGraphicsBeginImageContext(CGSizeMake(64,64));
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    // drawing code here (using context)
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    【讨论】:

      【解决方案3】:

      类似这样的:

      UIGraphicsBeginImageContextWithOptions(mySize, NO, 0.0f);       
      CGContextRef context = UIGraphicsGetCurrentContext();
      UIGraphicsPushContext(context);
      
      [myImage drawInRect:myImageRect];
      [myText drawAtPoint:myOrigin withFont:myFont];
      
      UIGraphicsPopContext();
      UIImage *myNewImage = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
      

      【讨论】:

      • 请注意,您将希望使用 UIGraphicsBeginImageContextWithOptions 而不是 UIGraphicsBeginImageContext,以便以设备支持的比例进行绘制。使用 UIGraphicsBeginImageContext 在视网膜显示器上看起来很糟糕。
      • UIGraphicsPushContext(context); 和 UIGraphicsPopContext(); 可以删除,因为 UIGraphicsBeginImageContextWithOptions(mySize, NO, 0.0f); 和 UIGraphicsEndImageContext(); 已经这样做了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      相关资源
      最近更新 更多