Graphics Reference
In-Depth Information
CAGradientLayer
CAGradientLayer is used to generate a smooth gradient between two or more colors.
It's possible to replicate the appearance of a CAGradientLayer using Core Graphics to
draw into an ordinary layer's backing image, but the advantage of using a
CAGradientLayer instead is that the drawing is hardware accelerated.
Basic Gradients
We'll start with a simple diagonal gradient from red to blue (see Listing 6.6). The gradient
colors are specified using the colors property, which is an array. The colors array
expects values of type CGColorRef (which is not an NSObject derivative), so we need
to use the bridging trick that we first saw in Chapter 2 to keep the compiler happy.
CAGradientLayer also has startPoint and endPoint properties that define the
direction of the gradient. These are specified in unit coordinates , not points, so the top-left
corner of the layer is specified with {0, 0} and the bottom-right corner is {1, 1}. The
resulting gradient is shown in Figure 6.6.
Listing 6.6 A Simple Two-Color Diagonal Gradient
@interface ViewController ()
@property ( nonatomic , weak ) IBOutlet UIView *containerView;
@end
@implementation ViewController
- ( void )viewDidLoad
{
[ super viewDidLoad ];
//create gradient layer and add it to our container view
CAGradientLayer *gradientLayer = [ CAGradientLayer layer ];
gradientLayer. frame = self .containerView. bounds ;
[ self .containerView. layer addSublayer :gradientLayer];
//set gradient colors
gradientLayer. colors = @[ ( __bridge id )[ UIColor redColor ]. CGColor ,
( __bridge id )[ UIColor blueColor ]. CGColor ] ;
//set gradient start and end points
gradientLayer. startPoint = CGPointMake ( 0 , 0 );
gradientLayer. endPoint = CGPointMake ( 1 , 1 );
 
Search WWH ::




Custom Search