Gradient background in iOS without images

One way to set a gradient background to a UI component is to create an image with the gradient colors and then assign it as the background image of the component. The alternative presented in this post is the use of the class CAGradientLayer.

A CAGradientLayer object is defined by these properties:

  • colors. An array of CGColorRef objects defining the color of each gradient stop.
  • locations. An optional array of NSNumber objects defining the location of each gradient stop.
  • startPoint. The start point of the gradient when drawn in the layer’s coordinate space. Default value is (0.5, 0.0).
  • endPoint. The end point of the gradient when drawn in the layer’s coordinate space. Default value is (0.5, 1.0).
 The first step is to import the QuartzCore package into your class. Do this by selecting your project target, then selecting “Build Phases” and “Link Binary With Libraries”. Press the add button and search for QuartzCore.

Add QuartzCore

Add this line to your import section.

#import <QuartzCore/QuartzCore.h>

In this example we are setting the gradient as the background of our view. Add the next code into the viewDidLoad method of the view.

// Create the colors
UIColor *darkOp =
 [UIColor colorWithRed:0.62f green:0.4f blue:0.42f alpha:1.0];
UIColor *lightOp =
 [UIColor colorWithRed:0.43f green:0.76f blue:0.07f alpha:1.0];

// Create the gradient
CAGradientLayer *gradient = [CAGradientLayer layer];

// Set colors
gradient.colors = [NSArray arrayWithObjects:
    (id)lightOp.CGColor,
    (id)darkOp.CGColor,
    nil];

// Set bounds
gradient.frame = self.view.bounds;

// Add the gradient to the view
[self.view.layer insertSublayer:gradient atIndex:0];

Gradient iOS A

Try to change the default locations with this code:

gradient.locations = [NSArray arrayWithObjects:
    [NSNumber numberWithFloat:0.0f],
    [NSNumber numberWithFloat:0.2],
    nil];

Gradient iOS B

Share Button

3 Comments

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.