Hi,
Any suggestions how to create a line by clicking two new points then draw a line between them? I am trying to create a distance tool like the one in adobe acrobat.
Image Example
Hi,
Any suggestions how to create a line by clicking two new points then draw a line between them? I am trying to create a distance tool like the one in adobe acrobat.
Image Example
You can handle the mouse click event on the panel (for example) and retrieve the location of the click (using the event args). Store this location in an attribute. Do that for as many points as you need. In the panel paint event, call the parent paint, then draw the lines between your points.
Something like this should do it:
Point firstPoint;
Point seondPoint;
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
if (this.firstPoint == null) {
this.firstPoint = e.Location;
}
if (this.secondPoint == null) {
this.secondPoint = e.Location;
}
panel1.Invalidate();
}
private void panel1_Paint_1(object sender, PaintEventArgs e)
{
Using (pn as new Pen(Color.Blue, 5))
{
e.Graphics.DrawLine(pn, firstPoint, secondPoint);
}
}
EDIT: You also dont need to do CreateGraphics
to draw the line - in the Paint event you have a graphics object already.
Problem Solved!
EDIT: Here's the code:
private Point p1, p2;
List<Point> p1List = new List<Point>();
List<Point> p2List = new List<Point>();
private void Panel1_MouseDown(object sender, MouseEventArgs e)
{
if (p1.X == 0)
{
p1.X = e.X;
p1.Y = e.Y;
}
else
{
p2.X = e.X;
p2.Y = e.Y;
p1List.Add(p1);
p2List.Add(p2);
Invalidate();
p1.X = 0;
}
}
private void Panel1_Paint(object sender, PaintEventArgs e)
{
using(var p = new Pen(Color.Blue, 4))
{
for(int x = 0; x<p1List.Count; x++){
e.Graphics.DrawLine(p, p1List[x], p2List[x]);
}
}
}