ios - CGContext 引用为 UIImage

标签 ios uiimage cgcontext

尝试从绘制上下文创建 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 中,或将其发送到其他对象,或将其写入文件,无论您喜欢什么。

另外(不太重要):

  1. 不要CGContextRelease(context)。您没有创建、复制或保留它,因此您不应发布它。

  2. 不需要最后一个CGContextAddLineToPoint()CGContextFillPath 将隐式为您关闭路径。

关于ios - CGContext 引用为 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9660596/

相关文章:

ios - 在 objective-c 中的两点之间画线

ios - 无法在没有错误的情况下在自定义 UITableView 上添加 UIButton

ios - 为并排按钮添加约束

iphone - 如何在 UIImageView 中复制 MKMapView 的屏幕?

ios - 如何将路径添加到将删除像素的 UIImage?

ios - 来自存储在 iCloud 上的图像的 CGImage 看起来不对

xamarin.ios - 为什么这个 Core Graphics 绘图代码会生成不同的线宽?

iphone - 在后台线程上绘制上下文

ios - 'UIButton' 没有可见的@interface 声明选择器 'setTitle'

iphone - mktime(从 php)到 iphone 时间(字符串)