was successfully added to your cart.


Quick and Easy iPhone Gradients

The market for iPhone and iPad apps is competitive and sometimes a bit of extra eye-candy goes a long way. For a couple of projects I have had to give various items a gradient shaded background. There are two ways to do this. Core Graphics or Core Animation. Gradients in Core Graphics give you more customization and more control, but are more complex to implement, while gradients in Core Animation are simple, but may not be able to do everything you need. Here we are going to look are the fast Core Animation approach.

Make sure you #import <QuartzCore/QuartzCore.h>

To make a simple rectangular gradient all we need is to add a CAGradientLayer:

CAGradientLayer * gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = CGRectMake(0, 0, 80, 60);
gradientLayer.colors = [NSArray arrayWithObjects:(id)[[UIColor redColor] CGColor],(id)[[UIColor greenColor] CGColor], nil];
[self.window.layer addSublayer:gradientLayer];

This produces a rectangle that can be used in any view:

We can give the layer rounded corners by adding:

gradientLayer.cornerRadius = 10;

For more complex shapes we can set a mask for the gradient layer using a CAShapeLayer:
//Make shape – Triangle
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL,40.0f, 0.0f);
CGPathAddLineToPoint (path, NULL,80.0f, 60.0f);
CGPathAddLineToPoint (path, NULL,0.0f, 60.0f);

//Shape layer
CAShapeLayer * mask = [CAShapeLayer layer];
mask.path = path;
[gradientLayer setMask:mask];

//release path

UIButton with a gradient:


The graph I made for a project using Core Animation layers: