This is my drawing code to draw a custom line with mouse onto a Chart. Can you please help me to do it proper way ?
namespace Grafi
{
public partial class Form1 : Form
{
bool isDrawing = false;
Point prevPoint;
public Form1()
{
InitializeComponent();
}
private void chartTemperature_MouseDown(object sender, MouseEventArgs e)
{
isDrawing = true;
prevPoint = e.Location;
}
private void chartTemperature_MouseMove(object sender, MouseEventArgs e)
{
Pen p = new Pen(Color.Red, 2);
if (isDrawing)
{
Graphics g = chartTemperature.CreateGraphics();
g.DrawLine(p, prevPoint, e.Location);
prevPoint = e.Location;
numOfMouseEvents = 0;
}
p.Dispose();
}
private void chartTemperature_MouseUp(object sender, MouseEventArgs e)
{
isDrawing = false;
}
}
}
Problem is that when I resize form my line disappers. It disappers whenever onPaint event is raised.
Do you have any problems with your current implementation? Does it work, or do you just want to make the code better for an already working function.
I think you logic looks just fine. However, I would add a using clause to the Pen like this:
This way your Pen will be disposed even in case of any exceptions occuring after it's creation and your call to
Dispose
.However, you can also think of making the
Pen
a class variable so you don't have to create and dispose it each time you move the mouse.You need to store your line somewhere.
The steps you need to take are:
ArrayList<ArrayList<Point>>
- where eachArrayList<Point>
contains the list of points in one line.new ArrayList<Point>
) at the end of the list of linespaint
, iterate through all lines, and draw each point of each line in the array.If you don't store your lines somewhere, they will be lost. Does this make sense?
The other way of storing lines is by using a
Canvas
object, where the pixel-map of what is drawn is remembered and automatically drawn. If you don't mind not having your line data as vector points, and you might also want to use images or colours, then this might be a better approach.I posted a solution a while back on how to draw a line using mouse movements. This should work for you.
Basically what you can do is draw a line every time the mouse moves. If there was a previous line and youre still moving the mouse, erase the line and draw the new one. Note that this example offsets based on a specific
Panel
(myPanel1 in this example). Adjust accordingly. If you resize the control, you will need to redraw the line using the anchor point previous point.Try this... It is a stroke drawing method, implemented very simply and as close to your own code as possible. Stokes are individual collections of mouse movements. Every mouse move between down and up is recorded as a stroke, all the strokes are collected and then redrawn whenever the paint event is fired. This example is simple but could be a good starting point.
Note that you will have to add the paint handler for your chart object.