PAK
PAK

Reputation: 441

Swift: Fading two images while chaging frame

Can someone tell me how can I animate a cross dissolve transition while chaging the initial frame?

My code:

self.image = initialImage

UIView.transition(with: _self, duration: 10.0, options: [.transitionCrossDissolve, .allowUserInteraction], animations: {
     self.image = newImage
})

Also tried:

let transition = CATransition()
transition.duration = 10
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionFade
transition.delegate = self

self?.layer.add(transition, forKey: nil)

Changing the frame size while the animation runs leaves the initial image at the initial frame size, while the newImage adapts to the updated frame.

Thank you.

Upvotes: 0

Views: 31

Answers (1)

user3151675
user3151675

Reputation: 58029

For an easier approach, create two image view instances and animate the alpha of the first one, while changing the frame for both of them.

let firstImageView = UIImageView(image: UIImage(named: "first"))
firstImageView.frame = CGRect(x: 100, y: 100, width: 200, height: 200)

let secondImageView = UIImageView(image: UIImage(named: "second"))
secondImageView.frame = firstImageView.frame

//the second image view should obscure the first one, that's why it's the first in the array
let imageViews = [secondImageView, firstImageView]

imageViews.forEach { view.addSubview($0) }

let newFrame = CGRect(x: 50, y: 50, width: 100, height: 100)

UIView.animate(withDuration: 10) {
    firstImageView.alpha = 0

    imageViews.forEach { $0.frame = newFrame }
}

Upvotes: 1

Related Questions