CALayer opacity animation

前端 未结 2 915

I want to create a CALayer animation that gives sort of a \'flashy\' effect. For that I\'m trying to animate the \'opacity\' property, but my problem is that I have no idea wher

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-07 04:08

    The best way to accomplish this is to use an explicit animation (see guide) by creating an instance of CABasicAnimation and adding it to the layer.

    The code would look something like this:

    CABasicAnimation *flash = [CABasicAnimation animationWithKeyPath:@"opacity"];
    flash.fromValue = [NSNumber numberWithFloat:0.0];
    flash.toValue = [NSNumber numberWithFloat:1.0];
    flash.duration = 1.0;        // 1 second
    flash.autoreverses = YES;    // Back
    flash.repeatCount = 3;       // Or whatever
    
    [layer addAnimation:flash forKey:@"flashAnimation"];
    

    If you want to know when the animation is done you can set a delegate and implement the animationDidStop:finished: method, however it's best to use a completion block as that allows all the code to be in the same place. If you are writing for iOS 4 or OS X then you can use the excellent CAAnimationBlocks category to accomplish this.

提交回复
热议问题