O'Reilly logo

Programming iOS 4 by Matt Neuburg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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];
Two images of Mars combined side by side

Figure 15-1. Two images of Mars combined side by side

Additional ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required