I want to create a looping animation like this GIF:
I have one picture, these is clouds. I want to see an animation of looping clouds when I launch the app. I’m adding 2 imageView
with the same cloud picture. I use this code to do this:
cloudsImageView1.frame.origin.x = 0
cloudsImageView2.frame.origin.x = screenSize
UIView.animate(withDuration: 20.0, delay: 0.0, options: [.repeat, .curveLinear], animations: {
self.cloudsImageView1.frame = self.cloudsImageView1.frame.offsetBy(dx: -1 * screenSize, dy: 0.0)
self.cloudsImageView2.frame = self.cloudsImageView2.frame.offsetBy(dx: -1 * screenSize, dy: 0.0)
}, completion: nil)
But I have bad results with wrong direction and disappearing images. How to fix it?
2
Answers
To fix the issue with disappearing images and wrong direction, ensure that you reset the position of the image views once they move out of the screen. You can achieve a seamless loop by repositioning the views in the completion block of the animation.
Here’s a corrected example:
This ensures the clouds loop seamlessly without disappearing or moving in the wrong direction.
We can do this by adding the image views as subviews of a
UIView
, and then animate that "container" view.Since we are using a single image, we can run a repeating animation. When the animation "re-starts," it will reset the container view’s
.origin.x
to0.0
and it will appear as a seamless, infinite scroll.Quick example code: