Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I animate opacity using swift?

Could someone please provide me with an example of animating the opacity of an Image View in swift??

I couldn't even find a good example in objective 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)
}

I think I have most of this right (not completely sure though), could someone please help me?

element = an Image View

Thanks in advance!~

like image 437
PugLvr28 Avatar asked Nov 18 '14 13:11

PugLvr28


3 Answers

You can also write it like this:

animation.fromValue = 0.0
animation.toValue = 1.0

The whole code should be like this:

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")
like image 101
R.Wonder Avatar answered Oct 12 '22 11:10

R.Wonder


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
}
like image 41
ylin0x81 Avatar answered Oct 12 '22 10:10

ylin0x81


You can use this extension method (unless you want to modify the view's attributes itself):

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
    }
}
like image 36
SoftDesigner Avatar answered Oct 12 '22 09:10

SoftDesigner