如何检测ios swift中touchbegan和touchmoved动作的角度?

时间:2014-12-06 10:29:16

标签: ios swift

我应该如何使用ios swift检测touchbegan和touchmoved事件的角度。

我想在ios swift中检测uiview上完成的移动角度

1 个答案:

答案 0 :(得分:1)

这取决于你对角度的看法,但是假设水平为零

步骤

  • 触发陷阱起点
  • 触摸移动陷阱终点
  • 使用基本三角法计算角度。请注意,Swift中提供了所有标准C math API。

基本实现可能是

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()

        }
    }

}