views:

45

answers:

3

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?

A: 

In my opinion you need somehow call function loadView again in your program to get appreciated effect of turning for 180 degrees.

For rotating view I use different aproach. So it may help.

CGAffineTransform rotate = CGAffineTransformMakeRotation(k45degrees); button.transform = rotate;

where k45degrees = -.7853982

Vanya
+1  A: 

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.

Brad Larson
A: 

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.

macserv