Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How should i detect angle on touchbegan and touchmoved event using ios swift.

I want to detect angle for movements done on uiview in ios swift

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
182 views
Welcome To Ask or Share your Answers For Others

1 Answer

It depends on your perspective of angle but ill assume horizontal is zero

Steps are

  • trap start point on touch down
  • trap end point on touch move
  • calculate the angle using basic trigonometry. Note that all the standard C math API are available in Swift.

a basic implementation could be

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

        }
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...