Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image moving in loop animation - Swift

I am working on swift for past 4 months and working on this splash screen since 2 weeks. There's car in the middle of the screen and 2 Images (City & Terrain) moving in loop from Right to Left(RtoL) as background. Check below gif taken from my android app:

Taken from my Android app

I am only able to move background RtoL but only once. I tried with other animation options but none seemed to work. You can see these images are much wider than the actual screen, so there shouldn't be any problem. Check my approach below:

func animate(_ image: UIImageView) {
UIView.animate(withDuration: 1.0, delay: 0.0, options: [.curveLinear], 
animations: {image.center.x -= 10}, 
completion: {_ in self.animate(image)})}

My only requirement is to move image RtoL with no gap in loop like in the above gif.

Thanks :)

like image 935
VipiN Negi Avatar asked Dec 15 '22 01:12

VipiN Negi


2 Answers

So its like you have to move the background but wants to make it seems like the car is moving, So for that case: You have to make 3 different imageViews

  1. For the building background
  2. For the trees background
  3. For the car.

just like i have created this animation. enter image description here

And the images you want to move from LToR or RToL you would have to double up on imageviews, so that you can append the same image (as another instance) to the end of the first when the right edge of the image reaches the right edge of the screen

like this as show in the image below. enter image description here

And adding this code for the purpose of animation.

func animateBackground() {

    // Animate background
    // cityImage is the visible image
    // cityImage2 is the hidden image

    UIView.animate(withDuration: 12.0, delay: 0.0, options: [.repeat, .curveLinear], animations: {
        self.cityImage.frame = self.cityImage.frame.offsetBy(dx: -1 * self.cityImage.frame.size.width, dy: 0.0)
        self.cityImage2.frame = self.cityImage2.frame.offsetBy(dx: -1 * self.cityImage2.frame.size.width, dy: 0.0)
    }, completion: nil)

}
like image 114
Rahim Khalid Avatar answered Dec 27 '22 02:12

Rahim Khalid


Seems like you are only moving the image to the left, soon the image will be moved off-screen and you wouldn't be able to see it. Try re-setting the image back to its original position after each iteration of the animation. You can do it with CGAffineTransform like so:

func animate(_ image: UIImageView) {
    UIView.animate(withDuration: 5, delay: 0, options: .curveLinear, animations: { 
        image.transform = CGAffineTransform(translationX: -100, y: 0)
    }) { (success: Bool) in
        image.transform = CGAffineTransform.identity
        animate(image)
    }
}

Hope that helps

like image 41
Chan Jing Hong Avatar answered Dec 27 '22 02:12

Chan Jing Hong