0

There are dozens of excellent examples on here and elsewhere of how to use gradients by

-(void)drawRect:(CGRect)rect

However, I'm new to Quartz and it's likely I'm missing something. When I found this, it seems more intelligent to create a CAGradientLayer and then add it to my view with something like:

-(void)viewWillAppear
{
   CAGradientLayer *bgLayer = [BackgroundLayer blueGradient];
   bgLayer.frame = self.view.bounds;
   [self.view.layer insertSublayer:bgLayer atIndex:0];
}

Where the blueGradient is a separate class method (within BackgroundLayer.m) which creates the gradient, as follows:

+ (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;

}

So here's my question. What if instead of this simple linear gradient, I want to create a radial one? How can I extend blueGradient so that it can handle two dimensional gradients? Or what if I want to add gradients on top of gradients? the drawRect function seems so limiting.

Or maybe that's just the wrong approach... then what's the wiring that I'm missing? How do I add gradients to my view(s) using drawRect? I want to be sure I'm doing it in a modular way so I can add gradient overlays, etc, as additional layers as necessary.

Community
  • 1
  • 1
Meshach
  • 315
  • 1
  • 2
  • 16

1 Answers1

0

As of iOS 7, CAGradientLayer can only draw a linear gradient. It cannot draw a radial gradient.

You can either use the drawRect: approach, or you can draw your gradient into an image and display the image in a view or layer. You can draw it into a UIImage and display it in a UIImageView, or you can draw it into a CGImage and set it as the contents of a CALayer.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Can you give an example of the code for this? Obviously it's not this, but just the line like UIImage *bgLayer = [BackgroundLayer blueGradient], would be immensely helpful. – Meshach Jun 06 '14 at 15:56
  • Well it looks like I'm on my own for this one... regardless, you did answer part of the question... so the points are yours. – Meshach Jun 11 '14 at 16:16