MusicGrotesque TV
MusicGrotesque TV

Reputation: 15

Draw Line with Points outside of Bitmap

I have 2 Points a and b. Point a is inside the Bitmap but point b is not!

Show here.

How can I calculate the x and y values of Point c?

I have tried this:

double ratio = Math.Abs(a.x - b.x) / Math.Abs(a.y - b.y);
b.x = bm.Width;
b.y = a.y + 1 / ratio * Math.Abs(a.x - b.x);
Graphics.FromImage(bm).DrawLine(new Pen(Color.Gray), (float)a.x, (float)a.y, (float)b.x, (float)b.y);

but it only worked with Points like these All other 3 Directions did not work :(

Thanks in advance!

Upvotes: 0

Views: 227

Answers (1)

SomeRandomGuy
SomeRandomGuy

Reputation: 579

First of all, you don't need coordinates inside the bounds of image to draw a line. You can use

Graphics.FromImage(bm).DrawLine(new Pen(Color.Gray), (float)a.x, (float)a.y, (float)b.x, (float)b.y);

without modifying b.

If you really want to find C coordinates, you have to compute segment crossing points between [A; B] and four edge segments [0:0 ; Width:0] [Width:0 ; Width:Height], [Width:Height ; 0:Height] and [0:Height ; 0:0].

Here is a function of mine (founded and adapted a few years ago...) that you can adapt (it will be easy to understand what is Segment struct) to check every segment for an intersection :

public static PointF? GetCrossingPoint(Segment segment1, Segment segment2)
{
    PointF output = null;

    double x1, x2, x3, x4, y1, y2, y3, y4;

    x1 = segment1.StartPoint.X;
    x2 = segment1.EndPoint.X;
    x3 = segment2.StartPoint.X;
    x4 = segment2.EndPoint.X;

    y1 = segment1.StartPoint.Y;
    y2 = segment1.EndPoint.Y;
    y3 = segment2.StartPoint.Y;
    y4 = segment2.EndPoint.Y;

    double den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);

    if (den != 0)
    {
        double t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / den;
        double u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / den;

        if (t > 0 && t < 1 && u > 0 && u < 1)
        {
            output = new PointF(x1 + t * (x2 - x1), y1 + t * (y2 - y1)));
        }
    }

    return output;
}

Upvotes: 2

Related Questions