[英]How to rotate an UIImageView using TouchesMoved
我正在嘗試使用Touch事件旋轉UIImageView
,我希望圖像可以用手指旋轉,我希望這樣做是一樣的: dropbox鏈接 (最好看一下,所以你明白我的意思了)
研究了如何旋轉UIImageView之后: 如何將UIImageView旋轉20度 。 我已經用開發iPhone應用程序的簡單方法嘗試了以下代碼:
class ViewController: UIViewController {
var startpoint:CGPoint!
var endpoint:CGPoint!
@IBOutlet var yello:UIImageView
override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
let t:UITouch = touches.anyObject() as UITouch
startpoint = t.locationInView(self.view)
endpoint = t.previousLocationInView(self.view)
if t.view == yello {
var startX = startpoint.x
var endX = endpoint.x
yello.center = CGPointMake(yello.center.x, yello.center.y)
UIView.animateWithDuration(1, animations: { self.yello.transform = CGAffineTransformMakeRotation(startX-endX)})
}
}
}
我可以清楚地看到我的代碼有很多錯誤和不良做法,並且也無法正常運行。 (請參見上方的保管箱鏈接)
因此,也許有更好的方法也許可以通過使用CoreAnimation來做到這一點,如果代碼示例能夠達到我想要的效果,我將不勝感激。
我只是寫了這么快。 我認為這就是您要尋找的。 我沒有使用圖像,而是使用了彩色視圖,但是您可以輕松地用圖像替換它。
您可能想要檢測是否拖動了視圖,以便用戶必須按順序拖動視圖才能旋轉,因為當前用戶可以拖動任何位置以旋轉視圖。
(下面的代碼現在檢查這種情況)如果您對此有任何疑問,請告訴我。
class ViewController: UIViewController {
var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
myView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
myView.center = self.view.center
myView.backgroundColor = UIColor.redColor()
self.view.addSubview(myView)
myView.layer.anchorPoint = CGPoint(x: 1.0, y: 0.5)
let box = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
box.backgroundColor = UIColor.blueColor()
myView.addSubview(box)
}
override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
let touch = touches.anyObject() as UITouch
if touch.view === myView.subviews[0] {
let position = touch.locationInView(self.view)
let target = myView.center
let angle = atan2(target.y-position.y, target.x-position.x)
myView.transform = CGAffineTransformMakeRotation(angle)
}
}
}
//更新了Swift 4的代碼
class ViewController: UIViewController {
var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
myView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
myView.center = self.view.center
myView.isUserInteractionEnabled = true
myView.backgroundColor = UIColor.red
self.view.addSubview(myView)
myView.layer.anchorPoint = CGPoint(x: 1.0, y: 0.5)
let box = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
box.backgroundColor = UIColor.blue
myView.addSubview(box)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch:UITouch = touches.first!
if touch.view === myView.subviews[0] {
let position = touch.location(in: self.view)
let target = myView.center
let angle = atan2(target.y-position.y, target.x-position.x)
myView.transform = CGAffineTransform(rotationAngle: angle)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.