Search code examples
ioscgcolorspace

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?


Solution

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