Graphics Reference
In-Depth Information
that layer, we then needed to do a complicated hit test to determine if the click was
within the desired shape or outside of it.
Fortunately, with the update to Core Animation that was included in iPhone OS 3.0 and
Mac OS X 10.6 Snow Leopard, there is another option: the
CAShapeLayer
, which is specifi-
cally designed to solve this issue. With
CAShapeLayer
, you can specify the path for any
shape by creating a Core Graphics path and assign it to the
CAShapeLayer
's
path
property.
You can then specify a fill color for the shape using
-setFillColor
on the layer.
Listing 10-1 demonstrates how to create a
CAShapeLayer
and add it to the layer tree. In
this example, a new
CAShapeLayer
is created, and it is instructed to take on the shape of a
simple triangle.
LISTING 10-1
Initializing a CAShapeLayer and Adding It to the Layer Tree
- (
void
)viewDidLoad
{
[
super
viewDidLoad
];
UIImage
*balloon = [
UIImage imageNamed
:
@”balloon.jpg”
];
[[[
self
view
]
layer
]
setContents
:(
id
)[balloon CGImage]];
CGMutablePathRef
path =
CGPathCreateMutable
();
CGPathMoveToPoint
(path,
NULL
, 0, 100);
CGPathAddLineToPoint
(path,
NULL
, 200, 0);
CGPathAddLineToPoint
(path,
NULL
, 200, 200);
CGPathAddLineToPoint
(path,
NULL
, 0, 100);
shapeLayer = [[
CAShapeLayer alloc
]
init
];
[shapeLayer
setBounds
:
CGRectMake
(0, 0, 200, 200)];
[shapeLayer
setFillColor
:[[
UIColor purpleColor
]
CGColor
]];
[shapeLayer
setPosition
:
CGPointMake
(200, 200)];
[shapeLayer
setPath
:path];
[[[
self
view
]
layer
]
addSublayer
:shapeLayer];
}
The first thing you notice in Listing 10-1 is that it starts out with the
-viewDidLoad
method, which tells us that this code is for an iPhone project. We grab an image from the
main bundle by calling
[UIImage imageNamed:]
and then set the view's layer contents to
display the image. Next, create a Core Graphics path with a call to
CGPathCreateMutable
.
We add lines to the path to draw a rectangle. Next we create our shape layer giving it a
size of 200
200 pixels. We set the fill color to purple and then set its path to the path
we just created. Now, when we add the layer to the layer tree with a call to
-addSublayer
,
you can see something like the image in Figure 10-1.
×