尝试从绘制上下文创建 UIimage。 什么也没看到。我是否错过了什么,或者完全失去了理智?
代码
- (UIImage *)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(context, 100, 100);
CGContextAddLineToPoint(context, 150, 150);
CGContextAddLineToPoint(context, 100, 200);
CGContextAddLineToPoint(context, 50, 150);
CGContextAddLineToPoint(context, 100, 100);
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CGContextFillPath(context);
// Do your stuff here
CGImageRef imgRef = CGBitmapContextCreateImage(context);
UIImage* img = [UIImage imageWithCGImage:imgRef];
CGImageRelease(imgRef);
CGContextRelease(context);
return img;
}
最佳答案
我假设这不是 View 上的 -drawRect:
方法,因为返回值是错误的。 (-[UIView drawRect:]
返回 void
,而不是 UIImage*
。)
如果它位于 NSView 上,则意味着您必须直接调用它才能获取返回值。但这意味着 UIKit 尚未设置图形上下文,就像它在窗口中的 View 上调用 -drawRect:
之前通常所做的那样。
因此,您不应假设 UIGraphicsGetCurrentContext()
有效。可能为零(你检查过吗?)。
如果您只想要一个图像:使用 UIGraphicsBeginImageContext()
创建上下文,然后使用 UIGraphicsGetImageFromCurrentImageContext()
提取 UIImage
(不需要中介 CGImage
),然后使用 UIGraphicsEndImageContext()
进行清理。
如果您 try catch View 所绘制内容的图像:修复您的 -drawRect:
以返回 void,并找到其他方法将该 UIImage 从 View 中取出 - 要么将其存储在 ivar 中,或将其发送到其他对象,或将其写入文件,无论您喜欢什么。
另外(不太重要):
不要
CGContextRelease(context)
。您没有创建、复制或保留它,因此您不应发布它。不需要最后一个
CGContextAddLineToPoint()
。CGContextFillPath
将隐式为您关闭路径。
关于ios - CGContext 引用为 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9660596/