Search code examples
iosobjective-cxcodecalayer

CAGradientLayer sometimes not rendering


I have a CAGradientLayer drawing in the background on viewDidLoad. It works some of the time, but then sometimes it just doesn't render anything persistently until I restart my computer. I can't figure out why some of the time it would work and then other times it won't. It will work lets say 5 builds in a row and then it will just stop rendering. No errors. Anyone have experience with this?

Background Layer Method:

+ (CAGradientLayer*) morningGradient {

UIColor *mornTop = [UIColor colorWithRed:0.843 green:0.722 blue:0.667 alpha:1.000];
UIColor *mornBottom = [UIColor colorWithRed:0.584 green:0.733 blue:0.945 alpha:1.000];

NSArray *colors =  [NSArray arrayWithObjects:(id)mornTop.CGColor, mornBottom.CGColor, nil];

NSNumber *stopOne       = [NSNumber numberWithFloat:0.0];
NSNumber *stopTwo       = [NSNumber numberWithFloat:0.7];
NSNumber *stopThree     = [NSNumber numberWithFloat:1.0];

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

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

return headerLayer;
}

Draw Method:

-(void)drawGrad
{
NSLog(@"drawing gradient");
CAGradientLayer *bgLayer = [BackgroundLayer morningGradient];
bgLayer.frame = self.view.bounds;
[self.view.layer insertSublayer:bgLayer atIndex:0];
}

ViewDidLoad:

- (void)viewDidLoad
{
[self drawGrad];
[super viewDidLoad];
}

Solution

  • From the documentation of CGGradientCreateWithColors(colorSpace, colors, locations[]) you can read

    The locations array should contain the same number of items as the colors array.

    I'm assuming that the same is true for CAGradientLayer but can't find anything in the documentation. I'm making this assumption because it makes sense. How would you really interpret two colors and three locations? What should be the color at the third location?

    Change your code so that you pass the same number of colors as locations.