如何从当前的graphics上下文创build一个UIImage?

我想从当前的graphics上下文创build一个UIImage对象。 更具体地说,我的用例是一个用户可以画线的视图。 他们可能会逐渐绘制。 完成后,我想创build一个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是CFArrayReftypes的,并且每次调用touchesEnded:时都会被填充。 另外请注意,drawRect:可能会在用户绘制时被调用多次。

当用户完成后,我想创build一个代表graphics上下文的UIImage对象。 任何build议如何做到这一点?

您需要先设置graphics上下文:

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

UIImage * image = UIGraphicsGetImageFromCurrentImageContext();

如果你需要保持image ,一定要保留它!

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

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

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

Swift版本

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