Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my CGGradient not working with a preset UIColor?

I have this working code:

    NSMutableArray *shadowColors = [NSMutableArray arrayWithCapacity:2];
    color = [UIColor colorWithRed:0 green:0 blue:0 alpha:1]; // Declaration using components
    [shadowColors addObject:(id)[color CGColor]];
    color = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.0]; // Declaration using components
    [shadowColors addObject:(id)[color CGColor]];

    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColors(space, (CFArrayRef)shadowColors, NULL);
    CGColorSpaceRelease(space);

    CGFloat sw = 10.0; // shadow width

    CGPoint top1 = CGPointMake(x, y+width/2.0);
    CGPoint top2 = CGPointMake(x + sw, y+width/2.0);

    CGPoint side1 = CGPointMake(x+width/2.0, y);
    CGPoint side2 = CGPointMake(x+width/2.0, y+sw);

    CGContextDrawLinearGradient(c, gradient, top1, top2, 0);
    CGContextDrawLinearGradient(c, gradient, side1, side2, 0);
    CGGradientRelease(gradient);

The color declarations are the part I'm interested in, lines 2 and 4. When I declare them as shown, they work just fine, but if I replace those two lines with the equivalent (I thought, at least) [UIColor blackColor] and [UIColor clearColor] then my gradients disappear. The colors I use don't make any difference, I can use greenColor and redColor and they still don't work.

Am I missing something or is this a bug in Apple's frameworks?


The code that doesn't work. And this is just the first section, everything else is the same.

    NSMutableArray *shadowColors = [NSMutableArray arrayWithCapacity:2];
    color = [UIColor blackColor];
    [shadowColors addObject:(id)[color CGColor]];
    color = [UIColor clearColor];
    [shadowColors addObject:(id)[color CGColor]];
like image 955
kubi Avatar asked Oct 10 '10 13:10

kubi


1 Answers

The code looks fine to me. blackColor and clearColor are probably both in a white color space, but the documentation says CGGradientCreateWithColors will convert the colors to the color space you pass in, so that shouldn't matter.

The only thing I can think of would be to try passing NULL for the color space, letting the gradient convert the colors to Generic RGB instead of Device RGB. This may work, but shouldn't make a difference—as far as I can see, it should work either way.

I suggest filing a bug.

like image 70
Peter Hosey Avatar answered Oct 20 '22 19:10

Peter Hosey