Find the CGPoint on a UIView rectangle intersected by a straight line at a given angle from the center point

后端 未结 2 1453
天命终不由人
天命终不由人 2020-12-09 05:37

In iOS, I\'m trying to determine the point on a rectangle intersected by an imaginary line from the center point to the perimeter of the rectangle at a predetermined angle.<

2条回答
  •  失恋的感觉
    2020-12-09 06:22

    here's Rob's answer as a swifty lil copy n paste.

    func findEdgePoint(angle: CGFloat) -> CGPoint {
    
        let intersection: CGPoint
    
        let xRad = frame.width / 2
        let yRad = frame.height / 2
    
        let tangent = tan(angle)
        let y = xRad * CGFloat(tangent)
    
        if fabs(y) <= yRad {
    
            if angle < CGFloat.pi / 2 || angle > 3 * CGFloat.pi / 2 {
                intersection = CGPoint(x: xRad, y: y)
            } else {
                intersection = CGPoint(x: -xRad, y: -y)
            }
        } else {
    
            let x = yRad / CGFloat(tangent)
    
            if angle < CGFloat.pi {
                intersection = CGPoint(x: x, y: yRad)
            } else {
                intersection = CGPoint(x: -x, y: -yRad)
            }
        }
    
        return intersection
    }
    
    // heck yeah rob, he's the man
    // if he can't solve it, no one can
    

提交回复
热议问题