Graphics Reference
In-Depth Information
▪
It doesn't get clipped to the layer
bounds
—A
CAShapeLayer
can happily draw
outside of its
bounds
. Your path will not get clipped like it does when you draw into
a regular
CALayer
using Core Graphics (as you saw in Chapter 2).
▪
There's no pixelation
—When you transform a
CAShapeLayer
by scaling it up or
moving it closer to the camera with a 3D perspective transform, it does not become
pixelated like an ordinary layer's backing image would.
Creating a
CGPath
CAShapeLayer
can be used to draw any shape that can be represented by a
CGPath
.
The shape doesn't have to be closed, and the path doesn't have to be unbroken, so you can
actually draw several distinct shapes in a single layer. You can control the
strokeColor
and
fillColor
of the path, along with other properties such as
lineWidth
(line
thickness, in points),
lineCap
(how the ends of lines look), and
lineJoin
(how the
joints between lines look); but you can only set these properties once, at the layer level. If
you want to draw multiple shapes with different colors or styles, you have to use a separate
layer for each shape.
Listing 6.1 shows the code for a simple stick figure drawing, rendered using a single
CAShapeLayer
. The
CAShapeLayer
path
property is defined as a
CGPathRef
, but
we've created the path using the
UIBezierPath
helper class, which saves us from
having to worry about manually releasing the
CGPath
. Figure 6.1 shows the result. It's not
exactly a Rembrandt, but you get the idea!
Listing 6.1
Drawing a Stick Figure Using
CAShapeLayer
#import
"DrawingView.h"
#import
<QuartzCore/QuartzCore.h>
@interface
ViewController ()
@property
(
nonatomic
,
weak
)
IBOutlet
UIView
*containerView;
@end
@implementation
ViewController
- (
void
)viewDidLoad
{
[
super
viewDidLoad
];
//create path
UIBezierPath
*path = [[
UIBezierPath
alloc
]
init
];
[path
moveToPoint
:
CGPointMake
(
175
,
100
)];