Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing gradient using CAGradientLayer on UIView not working

I'm trying to draw a gradient on the background view of a View Controller with but for some reason I couldn't get it to work.

Here is my method, which is called from viewDidLoad:

- (void)drawGradient
{
  CAGradientLayer *gradient = [CAGradientLayer layer];
  gradient.frame = self.view.bounds;

  gradient.colors = @[[UIColor greenColor], [UIColor redColor]];
  gradient.locations = @[@0.0, @1.0];

  [self.view.layer insertSublayer:gradient atIndex:0];
}

...but nothing happens, and the gradient doesn't appear. What am I doing wrong?

like image 343
WedgeSparda Avatar asked Sep 30 '15 09:09

WedgeSparda


1 Answers

Thanks to Larme's comment, I figured out my mistake.

Instead of

gradient.colors = @[[UIColor greenColor], [UIColor redColor]];

the right this is

gradient.colors = @[(id)[UIColor greenColor].CGColor, (id)[UIColor redColor].CGColor];

Because gradient.colors expects a NSArray of CGColorRef. The (id) cast is also needed in order to create the NSArray.

like image 115
WedgeSparda Avatar answered Oct 22 '22 07:10

WedgeSparda