我应该如何使用ios swift检测touchbegan和touchmoved事件的角度。
我想在ios swift中检测uiview上完成的移动角度
答案 0 :(得分:1)
这取决于你对角度的看法,但是假设水平为零
步骤
基本实现可能是
import UIKit
class AngleOfDangle:UIView {
var touchDown:CGPoint = CGPointZero
var endPoint:CGPoint = CGPointZero
var gotLock:Bool = false
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
//we want only one pointy thing
if touches.count == 1 {
gotLock = true
if let touch = touches.anyObject() as? UITouch {
touchDown = touch.locationInView(self)
}
}
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
if touches.count == 1 {
if let touch = touches.anyObject() as? UITouch {
endPoint = touch.locationInView(self)
let angle = self.angle(touchDown, end: endPoint)
println("the angle is \(angle)")
}
}
else {
gotLock = false
}
self.setNeedsDisplay()
}
func angle(start:CGPoint,end:CGPoint)->Double {
let dx = end.x - start.x
let dy = end.y - start.y
let abs_dy = fabs(dy);
//calculate radians
let theta = atan(abs_dy/dx)
let mmmm_pie:CGFloat = 3.1415927
//calculate to degrees , some API use degrees , some use radians
let degrees = (theta * 360/(2*mmmm_pie)) + (dx < 0 ? 180:0)
//transmogrify to negative for upside down angles
let negafied = dy > 0 ? degrees * -1:degrees
return Double(negafied)
}
override func drawRect(rect: CGRect) {
if gotLock {
var level = UIBezierPath()
level.moveToPoint(CGPointMake(0, touchDown.y))
level.addLineToPoint(CGPointMake(CGRectGetWidth(self.frame), touchDown.y))
level.stroke()
var path = UIBezierPath()
path.moveToPoint(touchDown)
path.addLineToPoint(endPoint)
path.stroke()
}
}
}