0

I'm using UIBezierPath to draw lines(in multiple angles) with two points, but I want to draw lines a little shorter than the distance between the two points.

I tried the following codes to find a point between the two points:

let x3 = x2 + 0.9 * (x1 - x2);
let y3 = y2 + 0.9 * (y1 - y2);

It works in 1 or 2 angles but fails in others. How can I get the correct point? Thanks.

=== Edited ===

enter image description here

By now I got some idea from the search, but I still cannot get it works

  1. Get the distance between the two points, and then minus 15, since I want it shorter

    let distance = sqrt(pow((p2.x - p1.x), 2) + pow((p2.y - p1.y), 2)) - 15
    
  2. Get the line angle:

    let angle = (p2.y - p1.y) / (p2.x - p1.x)
    
  3. Get point 3 with distance and angle:

    let x = p1.x + (distance * cos(angle))
    let y = p1.y - (distance * sin(angle))
    
jdleung
  • 1,088
  • 2
  • 10
  • 26
  • 1
    Your code computes a point (x3, y3) on the line connecting (x1, y1) with (x2, y2). A concrete example where you think it fails would be helpful (input, expected output, and actual output). – Martin R Apr 06 '19 at 15:36
  • That's a maths issue. Did you stop and draw it on a paper sheet? There are different ways of seeing it. For instance, you can check this: https://stackoverflow.com/questions/1934210/finding-a-point-on-a-line – Larme Apr 06 '19 at 15:51
  • @MartinR I posted some new code, just don't know if it's the right way. – jdleung Apr 07 '19 at 10:14
  • @jdleung: What is wrong with your original code? It is definitely a better approach than your added code. – Martin R Apr 07 '19 at 10:39
  • @MartinR `atan2` fixed the problem. Thanks. – jdleung Apr 07 '19 at 22:30
  • @Larme I found another way to solve it, thanks your answer. – jdleung Apr 07 '19 at 22:32

1 Answers1

2

It's a problem of wrong angle, function atan2 gives a correct angle value. Now the whole code work perfect.

let angle = atan2((p2.y - p1.y), (p2.x - p1.x))
jdleung
  • 1,088
  • 2
  • 10
  • 26