Search code examples
objective-cpointdirection

How to find the direction of the line in Cocoa?


Consider a line AB in Cartesian coordinates system. The length of the line is d.

What I need:

I want to draw an arrow in the point B, to represent the direction of the line.

What I tried:

I found a point C, which is placed in the line AB, before some x points of B. Then I tried to find points (P & Q) with respect to the line CB in 90 degrees. But it does not work for me.

Refer this image: enter image description here Rather than doing this complex steps, is there any other way to find the direction of the line to draw the correct arrow in right direction?

Please remember the line may lie in any direction. All I have is, the point A & B only.


Solution

    1. I do not think that the answer given in How can I find the points in a line - Objective c? is too complex. You can make it look a bit nicer by using CGPoint instead of (x, y) pairs.

    2. One input parameter is missing in your question: The desired size of the arrow, for example the distance from C to B.

    That being said, the following computation should help you.

    // Your points A and B:
    CGPoint A = CGPointMake(x1, y1);
    CGPoint B = CGPointMake(x2, y2);
    
    // Vector from A to B:
    CGPoint AB = CGPointMake(B.x - A.x, B.y - A.y);
    
    // Length of AB == distance from A to B:
    CGFloat d = hypotf(AB.x, AB.y);
    
    // Arrow size == distance from C to B.
    // Either as fixed size in points ...
    CGFloat arrowSize = 10.;
    // ... or relative to the length of AB:
    // CGFloat arrowSize = d/10.;
    
    // Vector from C to B:
    CGPoint CB = CGPointMake(AB.x * arrowSize/d, AB.y * arrowSize/d);
    
    // Compute P and Q:
    CGPoint P = CGPointMake(B.x - CB.x - CB.y, B.y - CB.y + CB.x);
    CGPoint Q = CGPointMake(B.x - CB.x + CB.y, B.y - CB.y - CB.x);
    

    P is computed from B by subtracting the vector CB = (CB.x, CB.y) first and then adding the perpendicular vector (-CB.y, CB.x).