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:.

A CGImage lets you create a new image directly from a rectangular region of the image. (It also lets you apply an image mask, which you can’t do with UIImage.) I’ll demonstrate by splitting the image of Mars in half and drawing the two halves separately (Figure 15-4):

UIImage* mars = [UIImage imageNamed:@"Mars.png"];
// extract each half as a CGImage
CGSize sz = [mars size];
CGImageRef marsLeft = CGImageCreateWithImageInRect([mars CGImage],
CGImageRef marsRight = CGImageCreateWithImageInRect([mars CGImage],
// draw each CGImage into an image context
UIGraphicsBeginImageContext(CGSizeMake(sz.width*1.5, sz.height));
CGContextRef con = UIGraphicsGetCurrentContext();
CGContextDrawImage(con, CGRectMake(0,0,sz.width/2.0,sz.height), marsLeft);
CGContextDrawImage(con, CGRectMake(sz.width,0,sz.width/2.0,sz.height), marsRight);
UIImage* im = UIGraphicsGetImageFromCurrentImageContext();
CGImageRelease(marsLeft); CGImageRelease(marsRight);
Image of Mars split in half

Figure 15-4. Image of Mars split in half

As already mentioned, ...

Get Programming iOS 4 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.