5

I have created a CAGradientLayer for my custom UIButtons. The code for creating it is as follows:

CAGradientLayer *gradient = [CAGradientLayer layer];

gradient.frame = btn.bounds;
gradient.cornerRadius = 10.0f;
locations=[[NSArray alloc] initWithObjects: LOC_0, LOC_5, LOC_51,LOC_1, nil]; 
[gradient setLocations:locations];
colorNext=[[NSArray alloc] initWithObjects:(id) G3_rgb1, (id) G3_rgb2, (id) G3_rgb3, (id) G3_rgb4, nil]; 
gradient.colors = colorNext;

[btn.layer insertSublayer:gradient atIndex:0];

My question is: on the press of the button I need to change the gradient view of the button by 180 degrees, how should I do this?

3 Answers 3

18

You can also change the start and end points of your gradient. The default startPoint is {0.5, 0.0}. The default endPoint is {0.5, 1.0}. Flip those to make your gradient go the other way.

[gradient setStartPoint:CGPointMake(0.5, 1.0)];
[gradient setEndPoint:CGPointMake(0.5, 0.0)];

Flip them back to display normally.

2

As long as you maintain a pointer to the gradient layer, you should be able to reverse the gradient color ordering by providing an inverted set of locations:

NSArray *newLocations = [[NSArray alloc] initWithObjects: [NSNumber numberWithFloat:(1.0 - [LOC_0 floatValue])], [NSNumber numberWithFloat:(1.0 - [LOC_5 floatValue])], [NSNumber numberWithFloat:(1.0 - [LOC_51 floatValue])], [NSNumber numberWithFloat:(1.0 - [LOC_1 floatValue])], nil]; 
[gradient setLocations:newLocations];
[newLocations release];

[gradient setNeedsDisplay];

(this would be cleaner if you had the float values for LOC_0, etc.)

I'm not sure if the -setNeedsDisplay is required, but it often is for content changes in a layer.

That said, Vanya's solution of applying a rotational transform may be the quickest way to achieve this effect.

As a comment, hopefully you have a [locations release] and [colorNext release] somewhere later in your code, otherwise you'll be leaking the locations and color arrays.

0

for swift 3.0+

gradient.startPoint = CGPoint(x: 0.5, y: 1.0)
 gradient.endPoint = CGPoint(x: 0.5, y: 0.0)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.