Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGGradientCreateWithColors returns a null pointer

The problem is described in the subj.; Here's my code below:

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor blueColor], nil];
CGGradientRef gradient = CGGradientCreateWithColors(NULL, (CFArrayRef)colors, NULL);

It's not working. Actually, the last call returns nil;

Neither it works when I replace the first argument NULL with a CGColorSpace reference, e.g. Device RGB.

What's wrong, does anyone have an idea?

like image 870
wh1t3cat1k Avatar asked Nov 27 '10 17:11

wh1t3cat1k


3 Answers

You need to access the CGColor cast from UIColor:

NSArray *colors = [NSArray arrayWithObjects:(id)[UIColor redColor].CGColor, (id)[UIColor blueColor].CGColor, nil];

Also, specifying a color space is recommended:

CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColors(space, (CFArrayRef)colors, NULL);
like image 198
Evan Mulawski Avatar answered Nov 13 '22 14:11

Evan Mulawski


CGGradientCreateWithColors() expects an array of CGColorRefs, not UIColors. AFAIK UIColor is not toll-free bridged with CGColorRef.

like image 20
Ole Begemann Avatar answered Nov 13 '22 13:11

Ole Begemann


CGFloat locations[2];
locations[0] = 0.0;
locations[1] = 1.0;

CGGradientRef gradient = CGGradientCreateWithColors(space, (CFArrayRef)colors, locations);
like image 21
Smyk Sergey Avatar answered Nov 13 '22 12:11

Smyk Sergey