Search code examples
iosobjective-cuibezierpathraytracing

Draw a Ray with 2 CGPoint Using UIBezierPath (IOS)


UIBezierPath *myPath = [[UIBezierPath bezierPath];
[myPath moveToPoint: firstPoint];
[myPath addLineToPoint: secondPoint];
myPath.lineWidth = 10;
[[UIColor yellowColor]setStroke];
[myPath stroke];

When I run this code, it will naturally draw a segment (From 1 point to another). I am trying to find a way to draw a ray. By this I mean draw from "firstPoint" through "secondPoint till the end of the screen. I don't mind if the ray point goes on forever (I guess).

Here what it would look like.

enter image description here

Thank you.

(if you need it, screen size 736x414 pixel)


Solution

  • You can calculate the slope of the line using the two points using the formula m = (y2-y1)/(x2-x1). Then calculate the third point by setting x and calculating y based on the slope. Make sure that you check for divide by 0.

    y3 = m (x3-x2) + y2

    Put x3 as the screen width which is 414 in your case. y1 is firstPoint.y and x2 is secondPoint.x and so on.

    Sample code

    CGPoint firstPoint = CGPointMake(50, 150);
    CGPoint secondPoint = CGPointMake(100, 250);
    CGPoint screenMax = CGPointMake(414,736);
    CGPoint lastPoint = CGPointZero;
    CGFloat slope = 1.0;
    if (secondPoint.x != firstPoint.x) {
        slope = (secondPoint.y - firstPoint.y) / (secondPoint.x - firstPoint.x);
        lastPoint = CGPointMake(screenMax.x, slope * (screenMax.x-secondPoint.x)+secondPoint.y);
    } else {
        slope = 0;
        lastPoint.x = secondPoint.x;
        lastPoint.y = screenMax.y;
    }
    UIBezierPath *myPath = [UIBezierPath bezierPath];
    [myPath moveToPoint: firstPoint];
    [myPath addLineToPoint: secondPoint];
    myPath.lineWidth = 10;
    [[UIColor yellowColor]setStroke];
    [myPath stroke];
    
    //this is the extension from the second point to the end of the screen
    [myPath addLineToPoint: lastPoint];
    [myPath stroke];