Ios – CAGradientLayer showing as solid color

core-animationios

I'm trying to set a gradient background on a view, but my code below makes the UIView appear solid black. If i change the whiteColor to greenColor, the gradient is displayed properly. Changing the backgroundColor of the layer to greenColor makes the view appear solid green.

My guess is that i'm dealing with some kind of transparency-issue, but i can't figure to work around it.

CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = [NSArray arrayWithObjects:
                                     (id)[[UIColor whiteColor] CGColor],
                                     (id)[[UIColor blackColor] CGColor], nil];
gradientLayer.frame = CGRectMake(0, 0, 1, someView.frame.size.height);

UIGraphicsBeginImageContext(CGSizeMake(1, someView.frame.size.height));
[gradientLayer renderInContext: UIGraphicsGetCurrentContext()];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

someView.backgroundColor = [UIColor colorWithPatternImage: image];

Best Answer

Your white and black colors are in grayscale colorspace. Try making them in RGB colorspace:

gradientLayer.colors = @[
    (id)[UIColor colorWithRed:0 green:0 blue:0 alpha:1].CGColor,
    (id)[UIColor colorWithRed:1 green:1 blue:1 alpha:1].CGColor
];

This should fix your issue, though I'm not sure of the Quartz mechanics behinds this.