Graphics Reference
In-Depth Information
CGMutablePathRef
circlePath =
CGPathCreateMutable
();
CGPathAddEllipseInRect
(circlePath,
NULL
,
self
.layerView2.
bounds
);
self
.layerView2.
layer
.
shadowPath
= circlePath;
CGPathRelease
(circlePath);
}
@end
For something like a rectangle or circle, creating a
CGPath
manually is fairly straight-
forward. For a more complex shape like a rounded rectangle, you'll probably find it easier
to use the
UIBezierPath
class, which is an Objective-C wrapper around
CGPath
provided by UIKit.
Using the
masksToBounds
property, we know that it is possible to clip a layer's contents
to its
bounds
, and using the
cornerRadius
property, we can even give it rounded
corners. But sometimes you will want to represent content that is not rectangular or even
rounded-rectangular in shape. For example, you might want to create a star-shaped photo
frame around an image, or you might want the edges of some scrolling text to fade
gracefully into the background instead of clipping to a sharp edge.
Using a 32-bit PNG image with an alpha component, you can specify a backing image that
includes an arbitrary alpha mask, which is usually the simplest way to create a non-
rectangular view. But that approach doesn't allow you to clip images dynamically using
programmatically generated masks or to have sublayers or subviews that also clip to the
same arbitrary shape.
CALayer
has a property called
mask
that can help with this problem. The
mask
property
is itself a
CALayer
and has all the same drawing and layout properties of any other layer.
It is used in a similar way to a sublayer in that it is positioned relative to its parent (the layer
that owns it), but it does not
appear
as a normal sublayer. Instead of being drawn inside the
parent, the
mask
layer defines the part of the parent layer that is visible.
The
color
of the
mask
layer is irrelevant; all that matters is its
silhouette.
The
mask
acts
like a cookie cutter; the solid part of the
mask
layer will be “cut out” of its parent layer and
kept; anything else is discarded (see Figure 4.12).
If the
mask
layer is smaller than the parent layer, only the parts of the parent (or its sub-
layers) that intersect the
mask
will be visible. If you are using a
mask
layer, anything
outside of that layer is implicitly hidden.