如何从当前图形上下文创建UIImage?

fig*_*ump 21 core-graphics quartz-graphics uiimage ios

我想从当前的图形上下文创建一个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);
}
Run Code Online (Sandbox Code Playgroud)

...其中_pathArray的类型为CFArrayRef,并且每次调用touchesEnded:时都会填充.另请注意,drawRect:可以在用户绘制时多次调用.

用户完成后,我想创建一个表示图形上下文的UIImage对象.有关如何做到这一点的任何建议?

小智 43

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

UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)


Ben*_*tow 7

UIImage*image = UIGraphicsGetImageFromCurrentImageContext();

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

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

UIGraphicsBeginImageContext(view.bounds.size);
[view drawRect: [myView bounds]];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)

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