【发布时间】:2010-11-09 22:07:18
【问题描述】:
我想从当前图形上下文创建一个 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 对象。有关如何执行此操作的任何建议?
【问题讨论】:
-
以下两个答案都有效。注意,两者在功能上有区别,就是在图像上下文中渲染图层也会渲染图层的背景;直接调用 drawRect: 不会(在我的情况下没关系)。由于直接调用 drawRect: 的复杂性,我将使用 CALayer renderInContext 方法(有关详细信息,请参阅lists.apple.com/archives/Cocoa-dev/2002/Apr/msg01846.html)。谢谢!
标签: ios uiimage core-graphics quartz-graphics