Gradient background for UIView in iOS

One of the pieces of code I find myself re-using constantly is creating a gradient background for a UIView in iOS. This example will show two examples of how to create a simple gradient background.

First, in Xcode, create a new Single View iOS application

Then create a new file File > New > New File and call this file “BackgroundLayer”, this will create BackgroundLayer.h and BackgroundLayer.m automatically for you.

Then copy the following code into the BackgroundLayer.h header file



#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>

@interface BackgroundLayer : NSObject

+(CAGradientLayer*) greyGradient;
+(CAGradientLayer*) blueGradient;

@end

Then copy the following code into the BackgroundLayer.m file



#import "BackgroundLayer.h"

@implementation BackgroundLayer

//Metallic grey gradient background
+ (CAGradientLayer*) greyGradient {

    UIColor *colorOne = [UIColor colorWithWhite:0.9 alpha:1.0];
    UIColor *colorTwo = [UIColor colorWithHue:0.625 saturation:0.0 brightness:0.85 alpha:1.0];
    UIColor *colorThree     = [UIColor colorWithHue:0.625 saturation:0.0 brightness:0.7 alpha:1.0];
    UIColor *colorFour = [UIColor colorWithHue:0.625 saturation:0.0 brightness:0.4 alpha:1.0];

    NSArray *colors =  [NSArray arrayWithObjects:(id)colorOne.CGColor, colorTwo.CGColor, colorThree.CGColor, colorFour.CGColor, nil];

    NSNumber *stopOne = [NSNumber numberWithFloat:0.0];
    NSNumber *stopTwo = [NSNumber numberWithFloat:0.02];
    NSNumber *stopThree     = [NSNumber numberWithFloat:0.99];
    NSNumber *stopFour = [NSNumber numberWithFloat:1.0];

    NSArray *locations = [NSArray arrayWithObjects:stopOne, stopTwo, stopThree, stopFour, nil];
    CAGradientLayer *headerLayer = [CAGradientLayer layer];
    headerLayer.colors = colors;
    headerLayer.locations = locations;

    return headerLayer;

}

//Blue gradient background
+ (CAGradientLayer*) blueGradient {

    UIColor *colorOne = [UIColor colorWithRed:(120/255.0) green:(135/255.0) blue:(150/255.0) alpha:1.0];
    UIColor *colorTwo = [UIColor colorWithRed:(57/255.0)  green:(79/255.0)  blue:(96/255.0)  alpha:1.0];

    NSArray *colors = [NSArray arrayWithObjects:(id)colorOne.CGColor, colorTwo.CGColor, nil];
    NSNumber *stopOne = [NSNumber numberWithFloat:0.0];
    NSNumber *stopTwo = [NSNumber numberWithFloat:1.0];

    NSArray *locations = [NSArray arrayWithObjects:stopOne, stopTwo, nil];

    CAGradientLayer *headerLayer = [CAGradientLayer layer];
    headerLayer.colors = colors;
    headerLayer.locations = locations;

    return headerLayer;

}

@end

Then finally, in your ViewController #import “BackgroundLayer.h” and add the following code to the viewWillAppear method:



CAGradientLayer *bgLayer = [BackgroundLayer blueGradient];
bgLayer.frame = self.view.bounds;
[self.view.layer insertSublayer:bgLayer atIndex:0];

And don’t forget to add the QuartzCore framework to your project.

Run the project and you get a result like this:


Click here to download the project

Edit: Thanks to moi in the comments below, add the following code to your view controller so that the CALayer rotates with the view



- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    // resize your layers based on the view’s new bounds
    [[[self.subview.layer sublayers] objectAtIndex:0] setFrame:self.subview.bounds];
}

Advertisements

21 thoughts on “Gradient background for UIView in iOS

  1. This is a superb Xcode tutorial, thank you very much. I just have a few questions:

    1) Since iOS is drawing the gradient itself, does that mean that it will support the @2x requirements of the Retina display on devices like the iPhone 5?

    2) For testing purposes, I am trying to change the gradient by allowing the user to press a Round Rect button, but nothing happens, the gradient doesn’t change. Why?

    3) Is there any way to animate between different gradients in a loop? I think this has the potential to make an app background look great.

    Thanks for your time,

    Daniel

    • Yes this will support @2x devices. To change the gradient, keep a reference to the CAGradient layer then call the removeFromSuperlayer method and insert a different gradient.

  2. I’ve tried but unfortunately I’m missing something.. I get 11 errors! For example, at line 06 of BackgroundLayer.m I get “Expected a type”…
    I have really no idea what’s going on… Any idea?
    PS. I’m on xcode 4.5 with iOS 6 libraries.

    • I’ve added #import to AppDelegate.h, so I guess that ifthat it is not the right way that must be the problem.. I can’t figure out how to include it!

      • Yes, that was the problem, solved, thank’s!
        One last question, I don’t fully get either the part about viewWillAppear, where am I supposed to place the code?

  3. Pingback: iOS Links – Resources I Collected While Learning iOSThe PHP Coder's Judy Chop | The PHP Coder's Judy Chop

  4. This is a really cool code… You may want to add the following to make sure that the layer follows the size of the subview… If the subview autoresizes, then the layer will follow…

    – (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
    {
    // resize your layers based on the view’s new bounds
    [[[self.subview.layer sublayers] objectAtIndex:0] setFrame:self.subview.bounds];
    }

  5. Thanks for the code. I found that, even with moi’s suggestion, I got a correct plus a wrong-size gradient visible when rotating and moving between views. I added moi’s resize to viewDidAppear and shouldAutorotateToInterfaceOrientation to no effect. The cure was to use replaceSublayer instead of using insertSublayer: atIndex:0 every time viewWillAppear was called. My solution drew on code at http://stackoverflow.com/questions/3713292/replacesublayer-example – I hope this helps other people out.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s