Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Image Transition Animation in Swift

Below is the code that automatically transitions between different images, every 5 seconds. I want to add animations to the transitions i.e. fade, scroll from left, etc. How would I go about doing this in Swift? Thanks.

class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    imageView.animationImages = [
        UIImage(named: "brooklyn-bridge.jpg")!,
        UIImage(named: "grand-central-terminal.jpg")!,
        UIImage(named: "new-york-city.jpg")!,
        UIImage(named: "one-world-trade-center.jpg")!,
        UIImage(named: "rain.jpg")!,
        UIImage(named: "wall-street.jpg")!]

    imageView.animationDuration = 25.0
    imageView.startAnimating()
}
like image 302
user3318660 Avatar asked Nov 12 '14 23:11

user3318660


1 Answers

class ViewController: UIViewController {
        @IBOutlet weak var imageView: UIImageView!

        let images = [
                UIImage(named: "brooklyn-bridge.jpg")!,
                UIImage(named: "grand-central-terminal.jpg")!,
                UIImage(named: "new-york-city.jpg"),
                UIImage(named: "one-world-trade-center.jpg")!,
                UIImage(named: "rain.jpg")!,
                UIImage(named: "wall-street.jpg")!]
        var index = 0
        let animationDuration: NSTimeInterval = 0.25
        let switchingInterval: NSTimeInterval = 3

        override func viewDidLoad() {
                super.viewDidLoad()

                imageView.image = images[index++]
                animateImageView()
        }

        func animateImageView() {
                CATransaction.begin()

                CATransaction.setAnimationDuration(animationDuration)
                CATransaction.setCompletionBlock {
                        let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(self.switchingInterval * NSTimeInterval(NSEC_PER_SEC)))
                        dispatch_after(delay, dispatch_get_main_queue()) {
                                self.animateImageView()
                        }
                }

                let transition = CATransition()
                transition.type = kCATransitionFade
                /*
                transition.type = kCATransitionPush
                transition.subtype = kCATransitionFromRight
                */
                imageView.layer.addAnimation(transition, forKey: kCATransition)
                imageView.image = images[index]

                CATransaction.commit()

                index = index < images.count - 1 ? index + 1 : 0
        }
}

Implement it as a custom image view would be better.

like image 113
ylin0x81 Avatar answered Nov 08 '22 16:11

ylin0x81