有人可以请我提供一个在swift中动画图像视图的不透明度的示例吗?
我甚至无法在目标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)
}
我认为我有大部分权利(尽管不完全确定),有人可以帮助我吗?
元素=图像视图
提前致谢!〜
答案 0 :(得分:10)
如果你需要一个简单的动画,为什么不使用UIView的animateWithDuration:animations:
方法?
imageView.alpha = 0
UIView.animateWithDuration(1.0) {
imageView.alpha = 1
}
答案 1 :(得分:3)
您也可以这样写:
animation.fromValue = 0.0
animation.toValue = 1.0
整个代码应该是这样的:
let animation = CABasicAnimation(keyPath: "opacity")
animation.delegate = self
animation.fromValue = 0.0
animation.toValue = 1.0
animation.duration = 1.0
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
element.layer?.addAnimation(animation, forKey: "fade")
答案 2 :(得分:1)
如果有人希望像OP最初尝试的那样使用CABasicAnimation,那么他的原始代码存在的一个问题是他正在使用NSValue作为toValue。我把它切换到NSNumber,它对我有用。喜欢这个
fadeToVisible.fromValue = NSNumber(float: 0.0)
答案 3 :(得分:1)
您可以使用此扩展方法(除非您想修改view
's attributes本身):
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
}
}