Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Coordinates of intersection from two Line objects

Tags:

c#

math

wpf

I have two Line objects in C# WPF, and I'm trying to construct a method to work out the coordinates at which the lines intersect (if at all). After giving myself a headache reminding myself of high school maths to do this, I can't work out how to map it into programming format - anyone know how to do this?

Thanks very much, Becky

like image 762
Becky Green Avatar asked Jan 21 '23 22:01

Becky Green


2 Answers

I suppose your line objects are made up of two points. What you should do is get the equations of both lines.

Then you should solve the following equation:

equation-line1 = equation-line2

Calculate slope of a line:

    float _slope = 1e+10;
    if ((p2.x - p1.x) != 0)
        _slope = (p2.y - p1.y) / (p2.x - p1.x);

p1 = Point 1 of your line p2 = Point 2 of your line

Equation of a line:

y = ax + b

a = the slope you calculated b = the intersect

Solving the equation:

    a1 = p1.y - b1 * p1.x;
    a2 = q1.y - b2 * q1.x;

    x = (a1 - a2) / (b2 - b1);
    y = a2 + b2 * x;

vars:

  • b1 = slope line 1
  • b2 = slop line 2
  • q1 = point 1 of your 2nd line

So, x and y are the coordinates of the point where the two lines intersect

like image 84
S P Avatar answered Jan 24 '23 12:01

S P


This is more of a gee-whiz answer than a practical one, because if all you are doing is intersecting two lines it is very slow. However I thought it was worth a mention.

WPF has the ability to intersect any two shape outlines, including two lines, and tell you the location of the intersection.

Here is the general technique for intersecting two outlines (the edges, not the fill area):

var shape1 = ...;
var shape2 = ...;

var thinPen = new Pen(Brush.Transparent, 0.001);

var geometry1 = shape1.RenderedGeometry.GetWidenedPathGeometry(thinPen);
var geometry2 = shape2.RenderedGeometry.GetWidenedPathGeometry(thinPen);

var combined = Geometry.Combine(
                 geometry1,
                 geometry2,
                 GeometryCombineMode.Intersect,
                 shape2.TransformToVisual(shape1));

var bounds = combined.GetRenderBounds(thinPen);

If the shapes are known to have the same position the shape2.TransformToVisual(shape1) in the call to Geometry.Combine can be replaced with null.

This technique can be very useful, if, for example, you need to intersect a line with an arbitrary curve.

like image 27
Ray Burns Avatar answered Jan 24 '23 13:01

Ray Burns