RobinHu
RobinHu

Reputation: 384

Draw a perpendicular line

I have a line defined as P1,P2 and I am trying to draw a perpendicular line to that line. y = kx + m

var p = new PointF {X = 20, Y = 20};
var p2 = new PointF {X = 50, Y = 100};

//Calculate K
var k1 = (p2.X - p.X)/(float) (p2.Y - p.Y);
//Since k1*k2 = -1 for a perpendicular line:
var k2 = (1/k1)*-1;
//the lines intersect in p2.
var m2 = p2.Y - k2*p2.X;

//choose arbitrary X value
var p3 = new PointF {X = p2.X + 20};
p3.Y = (k2*p3.X) + m2;

var newK = (p3.X - p2.X)/(float)(p3.Y-p2.Y);

If I run this newK gets the value -0.375 when it should be -1.

EDIT: newK should be -2,666667 and not -1.

What am I missing?

Upvotes: 0

Views: 3326

Answers (1)

Eugeny89
Eugeny89

Reputation: 3731

It looks like you're having error in calculating k1. Coefficient k is dy over dx, so you should have k1 = (p2.Y - p.Y)/(p2.X - p.X).

Upvotes: 3

Related Questions