如何从当前图形上下文创建UIImage? [英] How to create a UIImage from the current graphics context?

查看:87
本文介绍了如何从当前图形上下文创建UIImage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to create a UIImage object from the current graphics context. More specifically, my use case is a view that the user can draw lines on. They may draw incrementally. After they are done, I'd like to create a UIImage to represent their drawing.

这是drawRect:现在对我来说是什么样的:

Here is what drawRect: looks like for me now:

- (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:可以在用户绘制时多次调用。

... where _pathArray is of type CFArrayRef, and is populated every time touchesEnded: is invoked. Also note that drawRect: may be invoked several times, as the user draws.

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

When the user is done, I'd like to create a UIImage object that represents the graphics context. Any suggestions on how to do this?

推荐答案

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

You need to setup the graphics context first:

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

这篇关于如何从当前图形上下文创建UIImage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆