Search code examples
cgimagerefuigraphicscontextdrawinrect

draw CGImageRef (not UIImage) into image context


Here's exactly how to draw a UIImage in to context:

UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
[someUIImage drawInRect:CGRectMake(...)];
[someOtherUIImage drawInRect:CGRectMake(...)];
[someOtherUIImage drawInRect:CGRectMake(...)];
UIImage *yourResult = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

No problem. However, say I have a CGImageRef which was built up somehow.

CGImageRef happyImageRef = CGImageCreateWithImageInRect(blah blah);

I want to draw it in to the context.

UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
[ happyImageRef .. somehowDrawInRect:CGRectMake(...)];
UIImage *yourResult = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

How do you do that?

To be clear, obviously you can just convert it to a UIImage

UIImage *wasteful = [UIImage imageWithCGImage:happyImageRef];

But that seems incredibly inefficient. How to do it?

I'm sure I'm confused or missing something simple, so thanks.


Solution

  • Use CGContextDrawImage

    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
    CGContextDrawImage(UIGraphicsGetCurrentContext(),CGRectMake(...), happyImageRef);
    UIImage *yourResult = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();