更新答案:
要像您在评论中提到的那样为background image 设置动画,一种方法是为您的背景图像创建无缝图案并将其在屏幕上移动。例如,将 image1 跨屏移动,跟随 image2,将 image1 移回原位,将 image2 移回原位,重复。根据您实际使用它的目的,可能有一种更简单的方法来执行此操作,但这只是一个示例。我为这个例子做了一个simple background pattern,请随意使用。
func animateBackground() {
let animationOptions = UIViewAnimationOptions.Repeat | UIViewAnimationOptions.CurveLinear
let backgroundImage = UIImage(named:"backgroundPattern.jpg")!
var amountToKeepImageSquare = backgroundImage.size.height - self.view.frame.size.height
// UIImageView 1
var backgroundImageView1 = UIImageView(image: backgroundImage)
backgroundImageView1.frame = CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y, width: backgroundImage.size.width - amountToKeepImageSquare, height: self.view.frame.size.height)
self.view.addSubview(backgroundImageView1)
// UIImageView 2
var backgroundImageView2 = UIImageView(image: backgroundImage)
backgroundImageView2.frame = CGRect(x: backgroundImageView1.frame.size.width, y: self.view.frame.origin.y, width: backgroundImage.size.width - amountToKeepImageSquare, height: self.view.frame.height)
self.view.addSubview(backgroundImageView2)
// Animate background
UIView.animateWithDuration(6.0, delay: 0.0, options: animationOptions, animations: {
backgroundImageView1.frame = CGRectOffset(backgroundImageView1.frame, -1 * backgroundImageView1.frame.size.width, 0.0)
backgroundImageView2.frame = CGRectOffset(backgroundImageView2.frame, -1 * backgroundImageView2.frame.size.width, 0.0)
}, completion: nil)
// Have something in the foreground look like its moving
var square = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
square.frame.origin = CGPoint(x: self.view.frame.origin.x + 25, y: self.view.frame.size.height - 75)
square.backgroundColor = UIColor.darkGrayColor()
self.view.addSubview(square)
// Animate foreground
UIView.animateWithDuration(0.5, delay: 0, options: animationOptions, animations: {
square.transform = CGAffineTransformMakeRotation(33)
}, completion: nil)
}
你最终会得到这样的动画:
原答案:
我不完全确定您想要实现什么,但据我所知,您希望您的视图在重复每个动画时不会跳回到其起始位置。您可以通过将 UIView 的起点设置在视图左侧并将其终点设置在视图右侧来实现这一点。
func animateSquare() {
// Create our square with size of 50x50
var square = UIView(frame: CGRect(x: 0, y: self.view.frame.height / 2, width: 50, height: 50))
// Set its origin just off the left of the screen so it is not visible
square.frame.origin = CGPoint(x: 0 - square.frame.size.width, y: self.view.frame.height / 2)
square.backgroundColor = UIColor.blackColor()
self.view.addSubview(square)
// Setup animation and repeat
let animationOptions = UIViewAnimationOptions.Repeat | UIViewAnimationOptions.CurveLinear
UIView.animateWithDuration(2.0, delay: 0, options: animationOptions, animations: {
// Offset our square's frame by the width of the view + the width of the square
// This way it moves off the screen to the right completely
square.frame = CGRectOffset(square.frame, self.view.frame.width + square.frame.width, 0.0)
}, completion: nil)
}
你最终会得到这样的动画: