核心动画不适用于“alpha”价值

发布于 12-05 23:39 字数 466 浏览 2 评论 0原文

在此代码之前,我的电影图片 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:< 的代码/code> 周围,但我正在教授核心动画,所以我想知道为什么 CABasicAnimation 不能完成这样的简单任务?

Before this code, my movie pic alpha is set to 0,

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

Nothing happened, if I set alpha to 0.5 beforehand instead, the alpha remains at 0.5 and not animating to 1.

I've seen a code using UIView beginAnimations: around, but I'm teaching core animation so I wondered why CABasicAnimation can't do simple task like this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

各自安好2024-12-12 23:39:14
[CABasicAnimation animationWithKeyPath:@"opacity"];

UIView 将其公开为 alpha,而 CALayer 将其公开为 opacity

[CABasicAnimation animationWithKeyPath:@"opacity"];

UIView exposes this as alpha where as CALayer exposes this as opacity.

独孤求败2024-12-12 23:39:14

对于 Swift:

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

并且,在委托函数中animationDidStop ,你应该这样做:

extension ViewController: CAAnimationDelegate {

    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {   
        view.alpha = toValue
    }
}

For Swift:

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)

If you want to keep the final alpha value, you have to set the current view controller as the delegate of the opacity animation:

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
    }
}
蓝眸2024-12-12 23:39:14

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

@ohho answers the posted question. Mine will be a bit more generic. For a list what can and how be animated with CABasicAnimation please refer to Apple's documentation

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文