Graphics Programs Reference
In-Depth Information
For the More Curious: Programmatically Generating
Content
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
Delegation is the more common way to programmatically draw to a layer. This is how im-
plicit layers work, but you can also give an explicit layer a delegate. However, it is not a
good idea to assign a UIView as the delegate of an explicit layer. Use a controller object
instead. (A UIView is already the delegate of another layer, and bad things happen when a
view is the delegate of two layers.)
A layer sends the message drawLayer:inContext: to its delegate object when it is
being displayed. The delegate can then perform Core Graphics calls on this context.
@implementation Controller
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
if (layer == hypnoLayer)
{
UIImage *layerImage = [UIImage imageNamed:@"Hypno.png"];
CGRect boundingBox = CGContextGetClipBoundingBox(ctx);
CGContextDrawImage(ctx, boundingBox, [layerImage CGImage]);
}
}
@end
Search WWH ::




Custom Search