Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
In this chapter, you set a layer’s contents with an image file. Now let’s look at how to set a layer’s contents programmatically. There are two ways to draw to a layer using Core Graphics: subclassing and delegation. In practice, subclassing is the last thing you want to do. The only reason to subclass CALayer to provide custom content is if you need to draw differently depending on some state of the layer. If this is the approach you wish to take, you must override the method drawInContext:.
@implementation LayerSubclass
- (void)drawInContext:(CGContextRef)ctx
{
UIImage *layerImage = nil;
if (hypnotizing)
layerImage = [UIImage imageNamed:@"Hypno.png"];
else
layerImage = [UIImage imageNamed:@"Plain.png"];
CGRect boundingBox = CGContextGetClipBoundingBox(ctx);
CGContextDrawImage(ctx, boundingBox, [layerImage CGImage]);
}
@end