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 ...
Get Programming iOS 4 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.