我想要一个红色圆圈的图像从屏幕顶部移动到底部,就好像是一个穿过屏幕的流星。它确实会移动,但它会在没有动画的情况下以毫秒为单位移动。如何让它像带尾巴的流星一样平滑移动?
class ViewController: UIViewController {
let meteorImage = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.meteorImage.backgroundColor = .clear
self.meteorImage.frame = CGRect(x: 50, y: 0, width: 50, height: 50)
self.meteorImage.isHidden = false
self.meteorImage.image = #imageLiteral(resourceName: "success")
view.addSubview(self.meteorImage)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonPressed(_ sender: UIButton) {
let totalHeight = Int(view.frame.height)
var currentHeight = 0
while currentHeight < totalHeight {
self.meteorImage.backgroundColor = .clear
self.meteorImage.frame = CGRect(x: 50, y: currentHeight, width: 50, height: 50)
self.meteorImage.isHidden = false
self.meteorImage.image = #imageLiteral(resourceName: "success")
view.addSubview(self.meteorImage)
currentHeight += 1
}
}
}
答案 0 :(得分:1)
动画必须通过动画调用完成。
这是一种动画制作的简单方法。
UIView.animate(withDuration: 0.1, animations: {
// Apply Changes to frame.
})
另外考虑:不是做while循环,只需设置流星帧的最终位置,并将持续时间设置为您想要的时间。
let newFrame= CGRect(x: 50,
y: currentHeight,
width: 50,
height: 50)
UIView.animate(withDuration: 3.0, animations: {
// Apply Changes to frame.
self.meteorImage.frame = newFrame
})
如果您想让动画更复杂,可以在UIView上查看关键帧动画。