CGImage Drawing
The Core Graphics version of UIImage is CGImage (actually a CGImageRef). They are easily converted to one another: a UIImage has a CGImage property that accesses its Quartz image data, and you can make a UIImage from a CGImage using imageWithCGImage: or initWithCGImage: (in real life, you are likely to use their more configurable siblings, imageWithCGImage:scale:orientation: and initWithCGImage:scale:orientation:).
A CGImage lets you create a new image directly from a rectangular region of the original image, which you can’t do with UIImage. (A CGImage has other powers a UIImage doesn’t have; for example, you can apply an image mask to a CGImage.) I’ll demonstrate by splitting the image of Mars in half and drawing the two halves separately (Figure 15-9). Observe that we are now operating in the CFTypeRef world and must take care to manage memory manually; ARC won’t help us here (Chapter 12):
UIImage* mars = [UIImage imageNamed:@"Mars.png"]; // extract each half as a CGImage CGSize sz = [mars size]; CGImageRef marsLeft = CGImageCreateWithImageInRect([mars CGImage], CGRectMake(0,0,sz.width/2.0,sz.height)); CGImageRef marsRight = CGImageCreateWithImageInRect([mars CGImage], CGRectMake(sz.width/2.0,0,sz.width/2.0,sz.height)); // draw each CGImage into an image context UIGraphicsBeginImageContextWithOptions( CGSizeMake(sz.width*1.5, sz.height), NO, 0); CGContextRef con = UIGraphicsGetCurrentContext(); CGContextDrawImage(con, CGRectMake(0,0,sz.width/2.0,sz.height), marsLeft); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access