views:

583

answers:

1

Hi,

I am new to iPhone development and am currently toying with recreating a charting tool I developed for Silverlight.

Currently I'm using a gradient to 'fill' a rectangle representing a bar within a chart. Is it possible to animate this gradient so it changes colour when a user touches the bar within the chart.

I have looked through the Core Animation guides provided by Apple but cannot see a property which targets gradients. I suppose I could use a transition to fade between two rects, one of which has my starting gradient and the second with the 'touched' version but this would mean obviously drawing multiple rect objects for each bar with I assume extra performace overheads.

Any ideas?

+2  A: 

Yes, indeed you can animated gradients with Core Animation.

The CAGradientLayer class that came out in 3.0 has a nice API for rendering gradients into a layer and animating color and color-stop changes as well.

I did a post on this class a little while back, along with some sample code that's linked at the bottom. http://j.mp/gradientlayers

In the sample I animate the gradient by building a CABasicAnimation, but you can implicitly animate the change as well, by just passing a new array of colors to the gradient layer's colors property. Use implicit animations unless you have a reason not to.

Check that out and let me know if you have any questions specific to the UI you're trying to animate.

Joe Ricioppo
Thanks Joe - it's now working exactly as planned.Was slightly stumped as I didn't know you had to set the frame of the layer. Spent a good deal of time looking at a blank view until I realised my gradient layer had dimensions of 0,0,0,0...I do have a question for you if you have time - Is it possible to draw paths within each layer? I'm trying to add a stroke around each bar. All I'm able to do is add a stroke to a rect on the main view rather than to each layer. I assume this is because the drawing context is set to the UIView, not the layer but I can't find a way to move the context...
Carl Hovland
Yes, definitely. Layers are actually way nicer to work with for rendering anything like that. CALayer has built-in properties for cornerRadius, borderColor, borderWidth, backgroundColor, etc. So it's really easy to set up a bunch of layers and specify different visual attributes for each without using a graphics context at all. Checkout the CALayer docs for those properties. http://j.mp/6ad0fiIf you want to do custom Quartz drawing inside of the layer you can subclass the layer and implement -drawInContext: or set up a delegate that implements -drawLayer:inContext:
Joe Ricioppo
If your original question was answered you can mark it as so, then it's moved from the 'unanswered' list to 'answered', and I get some stack cred points too.
Joe Ricioppo