Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get UIImage from a CGContextRef?

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

Now, I would like to have a function call to get a UIImage for the CGContextRef. How do I do that?

like image 223
samwize Avatar asked May 03 '11 07:05

samwize


2 Answers

Something like this :

-(UIImage*)doImageOperation
{
  // Do your stuff here
  CGImageRef imgRef = CGBitmapContextCreateImage(context);
  UIImage* img = [UIImage imageWithCGImage:imgRef];
  CGImageRelease(imgRef);
  CGContextRelease(context);
  return img;
}
like image 170
Nyx0uf Avatar answered Oct 26 '22 22:10

Nyx0uf


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)
}
like image 40
Echelon Avatar answered Oct 26 '22 22:10

Echelon