如何在切换CALayers时进行动画处理

时间:2014-07-26 18:33:19

标签: ios objective-c calayer

我正在使用此方法添加和删除CALayers

[[[self.view.layer sublayers] objectAtIndex:0] removeFromSuperlayer];
    if(++self.backgroundIndex > self.gradients.count - 1) {
        self.backgroundIndex = 0;
    }
    CAGradientLayer *layer = [self.gradients objectAtIndex:self.backgroundIndex];
    layer.frame = self.view.frame;
    [self.view.layer insertSublayer:layer atIndex:0];

我该如何设置动画?感谢。

1 个答案:

答案 0 :(得分:1)

添加和删除此类内容CALayers时,您可以使用Core Animation

CABasicAnimation *fadeOut = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeOut.fromValue = [NSNumber numberWithFloat:1.0];
fadeOut.toValue = [NSNumber numberWithFloat:0.0];
fadeOut.duration = 1.0;        // 1 second

[[[self.view.layer sublayers] objectAtIndex:0] addAnimation:fadeOut forKey:@"fadeOutAnimation"];

//添加图层动画

CAGradientLayer *layer = [self.gradients objectAtIndex:self.backgroundIndex];

CABasicAnimation *fadeIn = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeIn.fromValue = [NSNumber numberWithFloat:1.0];
fadeIn.toValue = [NSNumber numberWithFloat:0.0];
fadeIn.duration = 1.0;        // 1 second

[layer addAnimation:fadeIn forKey:@"fadeInAnimation"];