我有一个 CGContextRef
并且使用位图上下文进行了绘画操作。
现在,我想调用一个函数来获取 CGContextRef
的 UIImage
。 我该怎么做?
我有一个 CGContextRef
并且使用位图上下文进行了绘画操作。
现在,我想调用一个函数来获取 CGContextRef
的 UIImage
。 我该怎么做?
类似于这样:
-(UIImage*)doImageOperation
{
// Do your stuff here
CGImageRef imgRef = CGBitmapContextCreateImage(context);
UIImage* img = [UIImage imageWithCGImage:imgRef];
CGImageRelease(imgRef);
CGContextRelease(context);
return img;
}
这是一个与Swift 3相关的方便函数,它接收一个CGContext并返回一个UIImage。请注意在Swift 3中使用完上下文后无需再释放它。
func imageFromContext(_ context: CGContext) -> UIImage? {
guard let cgImage = context.makeImage() else { return nil }
return UIImage.init(cgImage: cgImage)
}
UIImage* UIGraphicsGetImageFromImageContext(CGContextRef context)
可以使用。 - samwizecontext
是CGBitmapContext,这将起作用;它可能不适用于其他任何类型的CGContext。 @samwize:您应该给它命名为不同的内容。前缀是按约定的名称空间;Apple可能随时添加一个名为“UIGraphicsGetImageFromImageContext”的函数,无论是公共的还是私有的,如果他们这样做,你的代码将会出问题。请使用您自己的前缀。 - Peter Hosey