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

Ios 如何从当前图形上下文创建UIImage?,ios,uiimage,core-graphics,quartz-graphics,Ios,Uiimage,Core Graphics,Quartz Graphics,我想从当前图形上下文创建UIImage对象。更具体地说,我的用例是一个用户可以在上面画线的视图。他们可能会以递增的方式绘制。完成后,我想创建一个UIImage来表示他们的绘图 以下是drawRect:现在对我来说的样子: - (void)drawRect:(CGRect)rect { CGContextRef c = UIGraphicsGetCurrentContext(); CGContextSaveGState(c); CGContextSetStrokeColorWithColor(c

我想从当前图形上下文创建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);
}
-(void)drawRect:(CGRect)rect
{
CGContextRef c=UIGraphicsGetCurrentContext();
CGContextSaveGState(c);
CGContextSetStrokeColorWithColor(c[UIColor blackColor].CGColor);
CGContextSetLineWidth(c,1.5f);
对于(CFIndex i=0;i
。。。其中_pathArray的类型为CFArrayRef,并且在每次调用toucheSend:时填充。还请注意,在用户绘制时,drawRect:可能会被多次调用


用户完成后,我想创建一个表示图形上下文的UIImage对象。有什么建议吗?

UIImage*image=UIGraphicsGetImageFromCurrentImageContext()

如果您需要保留
图像
,请务必保留它

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

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

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

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

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

Swift版本

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

        return viewImage
    }

感谢您的回复,但是似乎不起作用。我添加了以下行:_signatureImage=UIGraphicsGetImageFromCurrentImageContext()。。。其中_signatureImage为保留财产。返回的对象为nil。根据文档,UIGraphicsGetImageFromCurrentImageContext()仅适用于当前上下文为位图上下文的情况。在我当前的drawRect实现中:我不认为是这样。文档中提到了UIGraphicsBeginImageContext()的使用,但我不确定这在我的案例中如何应用,因为drawRect可能会被多次调用。下面两个答案都适用。请注意,这两者之间有一个功能上的区别,即在图像上下文中渲染层也将渲染层的背景;直接调用drawRect并不重要(在我的情况下,这并不重要)。我使用CALayer RenderContext方法,因为直接调用drawRect:非常复杂(有关详细信息,请参阅)。谢谢