Graphics Reference
In-Depth Information
It can sometimes be beneficial to enable rasterization as an optimization for layers that
require offscreen rendering, but only if the layer/sublayers do not need to be redrawn
frequently.
For layers that require offscreen rendering
and
need to animate (or which have animated
sublayers), you may be able to use
CAShapeLayer
,
contentsCenter
, or
shadowPath
to
achieve a similar appearance with less of a performance impact.
CAShapeLayer
Neither
cornerRadius
nor
masksToBounds
impose any significant overhead on their own,
but when combined, they trigger offscreen rendering. You may sometimes find that you
want to display rounded corners and clip sublayers to the layer bounds, but you don't
necessarily need to clip to the rounded corners, in which case you can avoid this overhead
by using
CAShapeLayer
.
You can get the effect of rounded corners and still clip to the (rectangular) bounds of the
layer without incurring a performance overhead by drawing the rounded rectangle using the
handy
+bezierPathWithRoundedRect:cornerRadius:
constructor for
UIBezierPath
(see
Listing 15.1). This is no faster than using
cornerRadius
in itself, but means that the
masksToBounds
property no longer incurs a performance penalty.
Listing 15.1
Drawing a Rounded Rectangle Using
CAShapeLayer
#import
"ViewController.h"
#import
<QuartzCore/QuartzCore.h>
@interface
ViewController
()
@property
(
nonatomic
,
weak
)
IBOutlet
UIView
*layerView;
@end
@implementation
ViewController
- (
void
)viewDidLoad
{
[
super
viewDidLoad
];
//create shape layer
CAShapeLayer
*blueLayer = [
CAShapeLayer
layer
];
blueLayer.
frame
=
CGRectMake
(
50
,
50
,
100
,
100
);
blueLayer.
fillColor
= [
UIColor
blueColor
].
CGColor
;
blueLayer.
path
= [
UIBezierPath
bezierPathWithRoundedRect
:
CGRectMake
(
0
,
0
,
100
,
100
)
cornerRadius
:
20
].
CGPath
;