Graphics Reference
In-Depth Information
AppDelegate
as delegate for the layer so that we can receive events when drawing needs
to occur.
NSSegmentedControl
is bound to the
-zoom:
method, which sends an event every time
the segmented control changes state. The index of the selected segment is used to deter-
mine the image's current scale before displaying the image within the
CATiledLayer
. This
is accomplished by setting its
sublayerTransform
with a
CATransform3DMakeScale
call,
passing in the
x
and
y
values based on the segmented control (see Listing 12-4).
LISTING 12-4
-zoom:
- (
IBAction
)zoom:(
id
)sender
{
CGFloat
zoom = 1.0 / ([sender
selectedSegment
] + 1);
[[
view layer
]
setSublayerTransform
:
CATransform3DMakeScale
(zoom, zoom, 1.0)];
}
The final method you need to implement is a delegate of the
CATiledLayer
. This method
enables us to override the layer's
-drawInContext:
method without having to subclass
CALayer
. In the default implementation of
-drawInContext:
, it looks for a delegate and
checks to see if the delegate implements
-drawLayer:inContext:
. If both of those condi-
tions are true, the -
drawLayer:inContext:
is called, as shown in Listing 12-5.
LISTING 12-5
-drawLayer:inContext:
- (
void
)drawLayer:(
CALayer
*)layer inContext:(
CGContextRef
)context
{
[[
CIContext contextWithCGContext
:context
options
:
nil
]
drawImage
:
image
atPoint
:
CGPointMake
(0, 0)
fromRect
:
CGRectMake
(0, 0, 6064, 4128)];
}
This method uses the image initialized in
-awakeFromNib
and draws it into the context
using the image size as the rectangle for drawing. It should be noted that you don't need
to handle any form of zoom calculations, scaling, or transforms in this method. The
CATiledLayer
handles that automatically.
How Does This Work?
CATiledLayer
loads images into tiles, hence the name. Each tile corresponds to a level of
detail based on a tile size that you set. When you request a level of detail,
CATiledLayer
takes the original image, scales it to the desired size, and breaks it into individual tiles
before drawing the tiles on-screen. Because these tiles are cached by
CATiledLayer
, you
can scroll around the image and change levels of detail very quickly.
CATiledLayer
caches only so many tiles at once, and when it hits that limit it starts
dropping tiles out of the cache as needed. If we request that tile again in the future, it is