UIImage and Graphics Contexts
The function UIGraphicsBeginImageContext creates a graphics context suitable for use as an image and makes it the current context. You then draw into this context to generate the image. When you’ve done that, you call UIGraphicsGetImageFromCurrentImageContext to turn the context into a UIImage, and then UIGraphicsEndImageContext to dismiss the context. Now you have a UIImage that you can display in a UIImageView or draw into some other graphics context.
UIImage provides methods for drawing itself into the current context. We now know how to obtain an image context and make it the current context, so we can experiment with these methods. Here, I’ll draw two pictures of Mars side by side:
UIImage* mars = [UIImage imageNamed:@"Mars.png"]; CGSize sz = [mars size]; UIGraphicsBeginImageContext(CGSizeMake(sz.width*2, sz.height)); [mars drawAtPoint:CGPointMake(0,0)]; [mars drawAtPoint:CGPointMake(sz.width,0)]; UIImage* im = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
If I now hand this image im over to a visible UIImageView, the image appears onscreen (Figure 15-1). I could do this, for example, by creating the UIImageView in code, as before:
UIImageView* iv = [[UIImageView alloc] initWithImage:im]; [self.window addSubview: iv]; iv.center = self.window.center; [iv release];

Figure 15-1. Two images of Mars combined side by side
Additional ...
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