8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[iOS] 画像をフェードアニメーションで切り替えていく

Last updated at Posted at 2018-01-19
class SampleViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
    var images: [UIImage] = [
        UIImage(named: "sample_img1"),
        UIImage(named: "sample_img2"),
        UIImage(named: "sample_img3")
    ]
    let index = 0
    let animationDuration: TimeInterval = 1
    let switchingInterval: TimeInterval = 3

    override func viewDidLoad() {
        super.viewDidLoad()
        imageView.image = images[index]
        animateImageView()
    }

    // 画像をフェードで切り替えるアニメーション
    func animateImageView() {
        CATransaction.begin()
        CATransaction.setAnimationDuration(animationDuration)
        CATransaction.setCompletionBlock {
            DispatchQueue.main.asyncAfter(deadline: .now() + self.switchingInterval) {
                self.animateImageView()
            }
        }
        
        let transition = CATransition()
        transition.type = kCATransitionFade
        
        brandImageImageView.layer.add(transition, forKey: kCATransition)
        brandImageImageView.image = brandImages[nextBrandImagesIndex]
        
        CATransaction.commit()
        
        nextBrandImagesIndex = nextBrandImagesIndex < brandImages.count - 1 ? nextBrandImagesIndex + 1 : 0
    }
}

参考: stackoverflow「Adding Image Transition Animation in Swift」

8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?