0

I'm creating a gradient with the following code that I found in another stackoverflow post about drawing radial gradients in iOS

- (void)drawInContext:(CGContextRef)ctx
{ 
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"theme"] isEqualToString:@"black"]) {

    }

    size_t gradLocationsNum = 2;
    CGFloat gradLocations[2] = {0.0f, 1.0f};
    CGFloat gradColors[8] = {156/255.0f, 97/255.0f, 249/255.0f,1.0f,41/255.0f,131/255.0f,242/255.0f,1.0f};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocations, gradLocationsNum);
    CGColorSpaceRelease(colorSpace);

    CGPoint gradCenter= CGPointMake(self.bounds.size.width/2, self.bounds.size.height+100);
    float gradRadius = MAX(self.bounds.size.width , self.bounds.size.height) ;

    CGContextDrawRadialGradient(ctx, gradient, gradCenter, 0, gradCenter, gradRadius, kCGGradientDrawsAfterEndLocation);


    CGGradientRelease(gradient);
}

I don't know how to define CGFloat gradColors[8] = {156/255.0f, 97/255.0f, 249/255.0f,1.0f,41/255.0f,131/255.0f,242/255.0f,1.0f}; such that I can do something like:

CGFloat gradColors[8];

if ...
    gradColors[8] = {156/255.0f, 97/255.0f, 249/255.0f,1.0f,41/255.0f,131/255.0f,242/255.0f,1.0f};
else if ...
    gradColors[8] = {156/255.0f, 97/255.0f, 249/255.0f,1.0f,41/255.0f,131/255.0f,242/255.0f,1.0f};

Also: is there a way to convert a UIColor into this format?

Community
  • 1
  • 1
Apollo
  • 8,874
  • 32
  • 104
  • 192

1 Answers1

1

You can try using CGGradientCreateWithColors() which accept an array of CGColor.

eg.

CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)@[(id)aUIColor1.CGColor, (id)aUIColor2.CGColor], gradientLocations);
BB9z
  • 2,432
  • 1
  • 30
  • 36