下面是想要实现的动画效果:
接下来就剩下🚗。的动画了。
首先需要把🚗。的图片放到Asset里面。
同样的声明一个carImageView属性和期望的图片大小属性,这里需要多创建一个carAnimator来实现动画。
private let carSize = CGSize(width: 50, height: 45)
private var carImageView: UIImageView!
private var carAnimator: UIViewPropertyAnimator = UIViewPropertyAnimator(duration: 3.0, curve: .easeInOut, animations: nil)
同样的,这里需要在setupUI里面设置好carImageView的大小以及其他属性,然后设为可以互动,添加点击手势以及响应方法以便后面添加点击的动画,最后添加为视图的子view。
carImageView = UIImageView(frame: CGRect(x: 0, y: view.frame.height - 100, width: carSize.width, height: carSize.height))
carImageView.contentMode = .scaleToFill
carImageView.image = UIImage(named: "car_icon")
carImageView.isUserInteractionEnabled = true
carImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(userTapOnCar)))
view.addSubview(carImageView)
声明一个animateCarToRight方法,在里面先添加一个🚗。从左边移动到右边的动画,然后完成移动的动画后执行一个左右翻转的动画,并将其添加到animateLogo的闭包里面调用。
private func animateCarToRight() {
carAnimator.stopAnimation(true)
carAnimator.addAnimations {
// Move car to the bottom right of the screen
self.carImageView.frame = CGRect(origin: CGPoint(x: self.view.frame.width - self.carSize.width,
y: self.view.frame.height - 100),
size: self.carSize)
}
carAnimator.addCompletion { _ in
UIView.animate(withDuration: 0.5, animations: {
self.carImageView.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
}, completion: { _ in
})
}
carAnimator.startAnimation()
}
接下来在carImageView的点击响应方法里面添加判断carImageView.frame.origin.x 和view.frame.width/2的代码,如果大于则需要从右到左移动,小于则是从左到右移动。
@objc private func userTapOnCar() {
if carImageView.frame.origin.x > view.frame.width/2 {
// Destination is on the right, go back to the left