Graphics Reference
In-Depth Information
Although Core Foundation types behave like Cocoa objects at runtime (known as
toll-free
bridging
), they are not type compatible with
id
unless you use a
bridged cast.
To assign
the image of a layer, you actually need to do the following:
layer.contents = (
__bridge
id
)image.CGImage;
If you are not using ARC (Automatic Reference Counting), you do not need to include the
__bridge
part, but
why are you not using ARC?!
Let's modify the project we created in Chapter 1 to display an image rather than a
background color. We don't need the additional hosted layer any more now that we've
established that it's possible to create layers programmatically, so we'll just set the image
directly as the
contents
of the backing layer of our
layerView
.
Listing 2.1 shows the updated code. Figure 2.1 shows the results.
Listing 2.1
Setting a
CGImage
as the Layer
contents
@implementation
ViewController
- (
void
)viewDidLoad
{
[
super
viewDidLoad
];
//load an image
UIImage
*image = [
UIImage
imageNamed
:
@"Snowman.png"
];
//add it directly to our view's layer
self
.
layerView
.
layer
.
contents
= (
__bridge
id
)image.
CGImage
;
}
@end