3

I have this an array called self.gradientArray of colors. When I print it out it looks like this:

gradientsArray: (
    "UIDeviceRGBColorSpace 0.333333 0.811765 0.768627 1",
    "UIDeviceRGBColorSpace 0.333333 0.811765 0.768627 1" )

I want to convert this array into a CGFloat array. An example is like this:

CGFloat colors [] = {
                1.0, 1.0, 1.0, 1.0,
                1.0, 0.0, 0.0, 1.0
            };

I tried this and it didn't work. I'm new to Objective-C and the syntax so please help me.

CGFloat colors [] = self.gradientArray;

I want to use the CGFloat array in making gradients like this:

CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2);
2
  • enumerate objects use NSArray *stringArray = [string componentsSeparatedByString: @" "]; and do it Commented Apr 19, 2016 at 6:51
  • @PKT I don't think he really has an array of strings. I think he has a NSArray of UIColor objects, which, when you NSLog it, generates output much like he shared in his question. Commented Apr 19, 2016 at 7:07

1 Answer 1

2

The gradientsArray would appear to be an array of UIColor, in which case you could do something like:

NSArray *gradientsArray = @[[UIColor redColor], [UIColor blueColor]];

CGFloat colors[gradientsArray.count * 4];
NSInteger index = 0;
for (UIColor *color in gradientsArray) {
    CGFloat red, green, blue, alpha;
    [color getRed:&red green:&green blue:&blue alpha:&alpha];
    colors[index++] = red;
    colors[index++] = green;
    colors[index++] = blue;
    colors[index++] = alpha;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Works like a charm! Thanks Rob!
@Rob CGFloat colors[gradientsArray.count * 4]; What does 4 represents here ??
The OP wanted to populate his/her CGFloat array to be supplied to CGGradientCreateWithColorComponents with four component values of each color in the gradient array, namely each color’s respective red, blue, green, and alpha values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.