Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I rotate a CAGradientLayer by 180 degrees?

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?

like image 392
darshan Avatar asked Sep 07 '10 12:09

darshan


2 Answers

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.

like image 123
macserv Avatar answered Sep 19 '22 03:09

macserv


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.

like image 31
Brad Larson Avatar answered Sep 22 '22 03:09

Brad Larson