425,742 Members | 1,033 Online
Need help? Post your question and get tips & solutions from a community of 425,742 IT Pros & Developers. It's quick & easy.

# Draw line,using equation ax + by + c = 0

 P: 1 Hi All, could anyone help me with how to draw in picturebox (c#) line, using equation ax + by + c = 0. As a result from calculation I have calculate a, b,c, but now I need draw line to picturebox with this I try calculate: x=-c-y*b/a z=-c-a*x/b Expand|Select|Wrap|Line Numbers             double[] x = new double[2];             double[] y = new double[2];               x[0] = (-c - 0 * b) / a;             x[1] = (-c - 1 * b) / a;               y[0] = (-c - 1 * a) / b;             y[1] = (-c - 1 * a) / b;               x[0] = Math.Abs(x[0] * 400);             x[1] = Math.Abs(x[1] * 400);               y[0] = Math.Abs(400-y[0] * 400);             y[1] = Math.Abs(400-y[1] * 400);   But when i draw line using points x and y, i thing that line is draw wrong. Than you for help. Apr 15 '11 #1

Expert 100+
P: 1,501
I haven't done lines this way in a loooooong time haha, but I'll try to help you. As I understand it, a, b, and c define your line. Then you can calculate x for a given y, and y for a given x.

To calculate a, b, and c, you need two points. You can draw those two points to see the line between them. Create a new form and then override the OnPaint event. Make two points and draw them.

Expand|Select|Wrap|Line Numbers
1. protected override void OnPaint(PaintEventArgs e)
2. {
3.     Graphics g = e.Graphics;
4.
5.     Point p1 = new Point(50, 75);
6.     Point p2 = new Point(300, 125);
7.
8.     g.DrawLine(Pens.Black, p1, p2);
9. }

Now you can calculate a, b, and c from those points.

Expand|Select|Wrap|Line Numbers
1. float a = p1.Y - p2.Y;
2. float b = p2.X - p1.X;
3. float c = p1.X * p2.Y - p2.X * p1.Y;
Now we can calculate points... lets say we want to pick an x and calculate y. We need to rearrange our formula...

ax + by = 0
ax + by = -c
by = -c - ax
y = (-c - ax) / b
Keep in mind that b can't be zero when we do it this way. I believe this is the limitation of this method of line drawing. It maps every value of x to a single value for y. So if all your values of Y are at the same x value, there's no way to calculate it.

Anyway, now that we have a, b, and c, we can just pick values for X and calculate Y. Then we can draw them and see where they fit on our original line. This will tell us if we've made a mistake or not.

Expand|Select|Wrap|Line Numbers
1. if (b != 0)
2. {
3.     float newX1 = 75;
4.     float newY1 = (-c - a * newX1) / b;
5.
6.     float newX2 = 275;
7.     float newY2 = (-c - a * newX2) / b;
8.
9.     g.DrawLine(Pens.Red, newX1, newY1, newX2, newY2);
10. }