![](/img/trans.png)
[英]How to generate a dynamic light/dark mode UIImage from Core Graphics?
[英]How to create a UIImage from the current graphics context?
我想从当前的图形上下文创建一个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对象。 有关如何做到这一点的任何建议?
您需要先设置图形上下文:
UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
如果你需要保持image
,一定要保留它!
编辑:如果要将drawRect的输出保存到图像,只需使用UIGraphicsBeginImageContext
创建位图上下文,并使用新的上下文绑定调用drawRect函数。 这比在drawRect中保存您正在使用的CGContextRef更容易 - 因为该上下文可能没有与之关联的位图信息。
UIGraphicsBeginImageContext(view.bounds.size);
[view drawRect: [myView bounds]];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
您也可以使用Kelvin提到的方法。 如果您想从更复杂的视图(如UIWebView)创建图像,他的方法会更快。 绘制视图的图层不需要刷新图层,只需要将图像数据从一个缓冲区移动到另一个缓冲区!
Swift版本
func createImage(from view: UIView) -> UIImage {
UIGraphicsBeginImageContext(view.bounds.size)
view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let viewImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return viewImage
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.