2

I need to find the point (green dot) on the edges of any (not just squares) given rectangle (grey box) where a line(red line) starting from the centre of the rectangle would intersect the rectangle.

visualization

The function should look something like this:

func intersection(forAngle angle: CGFloat, rect: CGRect) -> CGPoint {
   // Do magic here
}

gist for easy visualisation that you can paste into a macOS playground

This is what I have so far:

let t = tan(angle)
switch angle {
case 0..<(pi/2):
  //top right corner - works but only for square rects
  // t > 1 => top edge, t < 1 right edge
  let x = t > 1 ? rect.width + (1 - t) * rect.width / 2 : rect.width
  let y = t < 1 ? t * rect.height / 2 + rect.height / 2 : rect.height
  return CGPoint(x: x, y: y)
case (pi/2)..<pi:
  //top left corner
case pi..<(1.5*pi):
  //bottom left corner
case 1.5*pi..<2*pi:
  //bottom right corner
default:
  return CGPoint.zero
}
dennism
  • 513
  • 5
  • 16
  • Have you done *anything* in an attempt to solve this problem? – Scott Hunter Sep 27 '16 at 23:10
  • @ScottHunter I tried to break down the rectangle into 4 corners and use tan, but I couldn't really get it to work for more than one side or non-squares (see edit) – dennism Sep 27 '16 at 23:25
  • 2
    All the math you need, and an Objective-C solution, are explained here: http://stackoverflow.com/q/9526726/77567 – rob mayoff Sep 28 '16 at 00:35

0 Answers0