开发者

How do I get UIImage from a CGContextRef?

开发者 https://www.devze.com 2023-03-02 23:37 出处:网络
I have a CGContextRef and I did my drawing stuff with the bitmap context. Now, I would like to have a function c开发者_C百科all to get a UIImage for the CGContextRef. How do I do that?Something like t

I have a CGContextRef and I did my drawing stuff with the bitmap context.

Now, I would like to have a function c开发者_C百科all to get a UIImage for the CGContextRef. How do I do that?


Something like this :

-(UIImage*)doImageOperation
{
  // Do your stuff here
  CGImageRef imgRef = CGBitmapContextCreateImage(context);
  UIImage* img = [UIImage imageWithCGImage:imgRef];
  CGImageRelease(imgRef);
  CGContextRelease(context);
  return img;
}


Updated for Swift 3, this is a convenience function that takes a CGContext and returns a UIImage. Note that you no longer need to free the context when you're done with it in Swift 3.

func imageFromContext(_ context: CGContext) -> UIImage? {
    guard let cgImage = context.makeImage() else { return nil }
    return UIImage.init(cgImage: cgImage)
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号