Graphics Reference
In-Depth Information
the -drawRect : method is present, it allocates a new backing image for the view, with
pixel dimensions equal to the view size multiplied by the contentsScale .
If you don't need this backing image, it's a waste of memory and CPU time to create it,
which is why Apple recommends that you don't leave an empty -drawRect: method in
your layer subclasses if you don't intend to do any custom drawing.
The -drawRect: method is executed automatically when the view first appears onscreen.
The code inside -drawRect: method uses Core Graphics to draw into the backing image,
and the result will then be cached until the view needs to update it (usually because the
developer has called the -setNeedsDisplay method, although some view types will be
redrawn automatically whenever a property that affects their appearance is changed [such
as bounds ]). Although -drawRect: is a UIView method, it's actually the underlying
CALayer that schedules the drawing and stores the resultant image.
CALayer has an optional delegate property that conforms to the CALayerDelegate
protocol. When CALayer requires content-specific information, it requests it from the
delegate. CALayerDelegate is an informal protocol, which is a fancy way of saying that
there is no actual CALayerDelegate @protocol that you can reference in your class
interface. You just add the methods you need and CALayer will call them if present. (The
delegate property is just declared as an id , and all the delegate methods are treated as
optional.)
When it needs to be redrawn, CALayer asks its delegate to supply a backing image for it
to display. It does this by attempting to call the following method:
- ( void )displayLayer:( CALayer CALayer *)layer;
This is an opportunity for the delegate to set the layer contents property directly if it
wants to, in which case no further methods will be called. If the delegate does not
implement the -displayLayer : method, CALayer attempts to call the following
method instead:
- ( void )drawLayer:( CALayer *)layer inContext:( CGContextRef )ctx;
Before calling this method, CALayer creates an empty backing image of a suitable size (based
on the layer bounds and contentsScale ) and a Core Graphics drawing context suitable
for drawing into that image, which it passes as the ctx parameter.
Let's modify the test project from Chapter 1 so that it implements the CALayerDelegate
protocol and does some drawing (see Listing 2.5). Figure 2.12 shows the result.
Listing 2.5 Implementing the CALayerDelegate
@implementation ViewController
- ( void )viewDidLoad
{
[ super viewDidLoad ];
Search WWH ::




Custom Search