【问题标题】:How to create a UIImage from the current graphics context?如何从当前图形上下文创建 UIImage?
【发布时间】:2010-11-09 22:07:18
【问题描述】:

我想从当前图形上下文创建一个 UIImage 对象。更具体地说,我的用例是用户可以在其上画线的视图。他们可能会逐渐绘制。完成后,我想创建一个 UIImage 来表示他们的绘图。

这就是 drawRect: 现在对我的样子:

- (void)drawRect:(CGRect)rect
{
CGContextRef c = UIGraphicsGetCurrentContext();

CGContextSaveGState(c);
CGContextSetStrokeColorWithColor(c, [UIColor blackColor].CGColor);
CGContextSetLineWidth(c,1.5f);

for(CFIndex i = 0; i < CFArrayGetCount(_pathArray); i++)
{
    CGPathRef path = CFArrayGetValueAtIndex(_pathArray, i);
    CGContextAddPath(c, path);
}

CGContextStrokePath(c);

CGContextRestoreGState(c);
}

... 其中 _pathArray 是 CFArrayRef 类型,每次调用 touchesEnded: 时都会填充。另请注意,drawRect: 可能会在用户绘制时被多次调用。

当用户完成后,我想创建一个表示图形上下文的 UIImage 对象。有关如何执行此操作的任何建议?

【问题讨论】:

  • 以下两个答案都有效。注意,两者在功能上有区别,就是在图像上下文中渲染图层也会渲染图层的背景;直接调用 drawRect: 不会(在我的情况下没关系)。由于直接调用 drawRect: 的复杂性,我将使用 CALayer renderInContext 方法(有关详细信息,请参阅lists.apple.com/archives/Cocoa-dev/2002/Apr/msg01846.html)。谢谢!

标签: ios uiimage core-graphics quartz-graphics


【解决方案1】:

您需要先设置图形上下文:

UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

【讨论】:

    【解决方案2】:

    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();

    如果您需要保留image,请务必保留它!

    编辑:如果您想将 drawRect 的输出保存到图像,只需使用 UIGraphicsBeginImageContext 创建一个位图上下文,并使用新的上下文绑定调用您的 drawRect 函数。这比在 drawRect 中保存您正在使用的 CGContextRef 更容易 - 因为该上下文可能没有与之关联的位图信息。

    UIGraphicsBeginImageContext(view.bounds.size);
    [view drawRect: [myView bounds]];
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    您也可以使用 Kelvin 提到的方法。如果你想从像 UIWebView 这样更复杂的视图中创建图像,他的方法更快。绘制视图的图层不需要刷新图层,只需将图像数据从一个缓冲区移动到另一个缓冲区!

    【讨论】:

    • 感谢您的回复,但似乎不起作用。我添加了这一行:_signatureImage = UIGraphicsGetImageFromCurrentImageContext(); ...其中 _signatureImage 是保留属性。返回的对象为零。根据文档, UIGraphicsGetImageFromCurrentImageContext() 仅在当前上下文是位图上下文时使用。在我当前的drawRect实现中:我不相信是这样。文档提到了 UIGraphicsBeginImageContext() 的使用,但我不确定这在我的情况下如何应用,因为 drawRect 可能会被多次调用。
    【解决方案3】:

    Swift 版本

        func createImage(from view: UIView) -> UIImage {
            UIGraphicsBeginImageContext(view.bounds.size)
            view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
            let viewImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            return viewImage
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多