wh1t3cat1k
wh1t3cat1k

Reputation: 3186

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?

Upvotes: 6

Views: 6560

Answers (3)

Evan Mulawski
Evan Mulawski

Reputation: 55354

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);

Upvotes: 17

Smyk Sergey
Smyk Sergey

Reputation: 21

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

CGGradientRef gradient = CGGradientCreateWithColors(space, (CFArrayRef)colors, locations);

Upvotes: 2

Ole Begemann
Ole Begemann

Reputation: 135588

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

Upvotes: 3

Related Questions