Search code examples
ioscore-animationcalayer

Animating CALayer opacity with pan gesture is not smooth


I have a CAGradientLayer overlaid on a CALayer. I want to animate it's opacity as I pan around the view they reside in.

So I simply have a CAGradientLayer instantiated like so:

this is how I instantiate the layer:

CAGradientLayer * gLayer = [CAGradientLayer layer];
NSArray * stops;
NSNumber *stopOne = [NSNumber numberWithFloat:0.0];
NSNumber *stopTwo = [NSNumber numberWithFloat:1.0];
[gLayer setColors:@[(id)clearColor.CGColor,(id)darkColor.CGColor]];
[gLayer setLocations:stops];

Then I change the opacity during the gesture: gLayer.opacity = (here I put the variable that changes between 0 - 1 as the pan changes)

So, even though this works, the change is not smooth because I am not animating it I guess.

How can I animate the opacity to be a fluid change? I guess the catch is that the animation has to be fast so that it follows the pan gesture change without lagging.

Any suggestion?

Thank you


Solution

  • The change will be fluid if you make an appropriate small change on every change in the gesture. The problem, in fact, is just the opposite of what you suspect: it is that the opacity is being animated, implicitly, but you keep canceling that animation because you do it again and again. Thus the change in opacity has no chance to become visible until the whole gesture is over. The solution, therefore, is to prevent the animation.

    So each time your gesture recognizer handler is called, if the state is UIGestureRecognizerStateChanged, you are going to turn off implicit animation and then change the opacity of the layer, like this:

    [CATransaction setDisableActions:YES];
    gLayer.opacity = whatever;
    

    Assuming that each whatever value is only slightly different from the previous whatever value, the result will be smooth. (But of course it is up to you to supply a sensible whatever value each time. I do not know whether you're doing that, as you have not revealed that part of your code.)