9

有人可以为我提供一个快速动画图像视图不透明度的示例吗?

我什至在目标 c 中找不到一个很好的例子

func showCorrectImage(element: AnyObject){

    var animation : CABasicAnimation = CABasicAnimation(keyPath: "opacity");

    animation.delegate = self

    animation.fromValue = NSValue(nonretainedObject: 0.0)
    animation.toValue = NSValue(nonretainedObject: 1.0)

    animation.duration = 1.0

    element.layer?.addAnimation(animation, forKey: nil)
}

我认为我拥有大部分权利(虽然不完全确定),有人可以帮助我吗?

元素 = 图像视图

先谢谢了!~

4

4 回答 4

15

If you need a simple animation, why not just use UIView's animateWithDuration:animations: method?

imageView.alpha = 0
UIView.animateWithDuration(1.0) {
        imageView.alpha = 1
}
于 2014-11-18T13:48:40.037 回答
9

你也可以这样写:

animation.fromValue = 0.0
animation.toValue = 1.0

整个代码应该是这样的:

let animation = CABasicAnimation(#keyPath(CALayer.opacity))
animation.fromValue = 0.0
animation.toValue = 1.0
animation.duration = 1.0
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
element.layer?.addAnimation(animation, forKey: "fade")
于 2016-05-10T13:20:50.703 回答
1

如果有人希望像 OP 最初尝试那样使用 CABasicAnimation,那么他原始代码的一个问题是他将 NSValue 用于 toValue。我将它切换到 NSNumber 并且它对我有用。像这样

    fadeToVisible.fromValue = NSNumber(float: 0.0)
于 2015-04-03T14:30:53.357 回答
1

您可以使用此扩展方法(除非您想修改view's 本身的属性):

extension CALayer {

    func flash(duration: TimeInterval) -> Observable<Void> {
        let flash = CABasicAnimation(keyPath: "opacity")

        flash.fromValue = NSNumber(value: 0)
        flash.toValue = NSNumber(value: 1)
        flash.duration = duration
        flash.autoreverses = true

        removeAnimation(forKey: "flashAnimation")
        add(flash, forKey: "flashAnimation")
        opacity = 0     // Change the actual data value in the layer to the final value
    }
}
于 2020-05-11T15:40:40.923 回答