35

在这段代码之前,我的电影图片 alpha 设置为 0,

CABasicAnimation* fadein= [CABasicAnimation animationWithKeyPath:@"alpha"];
    [fadein setToValue:[NSNumber numberWithFloat:1.0]];
    [fadein setDuration:0.5];
    [[moviepic layer]addAnimation:fadein forKey:@"alpha"];

什么都没有发生,如果我事先将 alpha 设置为 0.5,则 alpha 将保持在 0.5 并且不会设置为 1。

我看过一个代码UIView beginAnimations:,但我正在教核心动画,所以我想知道为什么 CABasicAnimation 不能完成这样的简单任务?

4

3 回答 3

105
[CABasicAnimation animationWithKeyPath:@"opacity"];

UIView 将其公开alpha为 CALayer 将其公开为opacity.

于 2011-09-23T03:12:16.790 回答
2

对于斯威夫特:

let opacity = CABasicAnimation(keyPath: "opacity")
opacity.fromValue = fromValue
opacity.toValue = toValue
opacity.duration = duration
opacity.beginTime = CACurrentMediaTime() + beginTime  //If a delay is needed

view.layer.add(opacity, forKey: nil)

如果要保留最终alpha值,则必须将当前视图控制器设置为不透明动画的委托:

opacity.delegate = self

And, in the delegate function animationDidStop, you should do:

extension ViewController: CAAnimationDelegate {

    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {   
        view.alpha = toValue
    }
}
于 2018-11-19T12:05:07.377 回答
1

@ohho 回答了发布的问题。我的会更通用一点。有关可以使用什么以及如何设置动画的列表,CABasicAnimation请参阅Apple 的文档

于 2015-10-28T10:57:44.570 回答