Graphics Programs Reference
In-Depth Information
Layer Content
A layer contains a bitmap called its
contents
, which can be set programmatically or
with an image. To set the contents programmatically, you either subclass
CALayer
or as-
sign a delegate to an instance of
CALayer
. The delegate then implements drawing
routines. (This is how implicit layers work; the view is its layer's delegate.)
We will discuss drawing to a layer programmatically at the end of this chapter. For now,
you're going to set the contents of the layer using an image file.
In
HypnosisView.m
, add the following code to the
initWithFrame:
method:
[boxLayer setBackgroundColor:cgReddish];
// Create a UIImage
UIImage *layerImage = [UIImage imageNamed:@"Hypno.png"];
// Get the underlying CGImage
CGImageRef image = [layerImage CGImage];
// Put the CGImage on the layer
[boxLayer setContents:(__bridge id)image];
// Inset the image a bit on each side
[boxLayer setContentsRect:CGRectMake(-0.1, -0.1, 1.2, 1.2)];
// Let the image resize (without changing the aspect ratio)
// to fill the contentRect
[boxLayer setContentsGravity:kCAGravityResizeAspect];
[[self layer] addSublayer:boxLayer];
In this code, we create an image and then get the underlying
CGImage
to use with Core
Graphics drawing. Then we set the image as the layer's contents and make adjustments for
how the contents appear within the layer.
Notice the use of
CGImageRef
and
CGColorRef
in this method. Why doesn't Core An-
imation use
UIImage
and
UIColor
?
The QuartzCore framework (which supplies the classes
CALayer
and
CAAnimation
)
and Core Graphics framework (which supplies
CGImageRef
) exist on both iOS and on
the Mac. UIKit (where we get
UIImage
and anything else prefixed with
UI
) only exists
on iOS. To maintain its portability, QuartzCore must use
CGImageRef
instead of
UIImage
. Fortunately, UIKit objects have methods to easily access their Core Graphics
counterparts, like
UIImage
's
CGImage
method you used in the previous code.