我有一个imageView,我想将舞台当前位置以恒定速度移动到分割位置,无论距离如何。
尝试了下面哪些方法不起作用,我真的不知道如何根据imageView需要遍历的距离来保持动画持续时间的动态。
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let position = touch.location(in: self.view)
print(position.x)
print(position.y)
CATransaction.begin()
CATransaction.setCompletionBlock { () -> Void in
self.imageView.layer.position = (self.imageView.layer.presentation()?.position)!
}
var animation = CABasicAnimation(keyPath: "position")
animation.duration = 2
var currentPosition : CGPoint = imageView.layer.presentation()!.position
animation.fromValue = NSValue(currentPosition)
animation.toValue = NSValue(CGPoint: position.x, (position.y))
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeForwards
imageView.layer.add(animation, forKey: "transform")
CATransaction.commit()
}
}
答案 0 :(得分:3)
试试这个
计算距离
func distance(_ a: CGPoint, _ b: CGPoint) -> CGFloat {
let xDist = a.x - b.x
let yDist = a.y - b.y
return CGFloat(sqrt((xDist * xDist) + (yDist * yDist)))
}
然后使用任意速度,计算时间
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let position = touch.location(in: self.view)
print(position.x)
print(position.y)
let distance = Double(self.distance(self.imageView.center, position))
let velocity = 100.0 //pixels by seconds
let time = distance / velocity
UIView.animate(withDuration: time, animations: {
self.imageView.center = position
})
}
}
答案 1 :(得分:0)
您可以添加imageView父视图的UITapGestureRecognizer并创建点按手势动作
@IBAction func tapGesture(_ sender: UITapGestureRecognizer) {
print("tap working")
if sender.state == UIGestureRecognizerState.recognized
{
let location = sender.location(in: sender.view)
print(location)
UIView.animate(withDuration: 0.5, animations: {
self.imageView.center = location
})
}
}