Is it really necessary to use an image? Can't you draw directly inside your form?
You can use the
MouseDown
event to get the click position, and
Paint
event to redraw your line:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Point point1 = new Point();
Point point2 = new Point();
bool firstPoint = true;
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawLine(Pens.Black, point1, point2);
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (firstPoint)
point1 = e.Location;
else
point2 = e.Location;
firstPoint = !firstPoint;
Invalidate();
}
}
-----------------
To your comment:
Yes I mean that.
In your example, you are using
Bitmaps
. Unless you want to save those bitmaps to a file (or load them from a file), there are not necessary. And actually it makes your code much more complicated. If your aim is drawing circles and lines inside your form, then just put all your drawing code in the
Paint
handler (as shown above) and use the
DrawLine
,
DrawEllipse
, or any method from the
Graphic
class. It will be much easier like that.
If you don't need the
MouseDown
handler then forget about it, it was just to show how to update drawings. Important things are
Invalidate
to force the form to redraw, the
Paint
handler to put drawing code, and
e.Graphics
to draw.
---------------
Here is an example of how to draw your grid:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Paint += new PaintEventHandler(Form1_Paint);
SizeChanged += new EventHandler(Form1_SizeChanged);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
}
int rows = 5;
int columns = 8;
int sizeOfDot = 10;
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.White, ClientRectangle);
float xOffset = (float)ClientRectangle.Width / (columns + 1);
float yOffset = (float)ClientRectangle.Height / (rows + 1);
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
{
PointF dot = new PointF((j + 1) * xOffset, (i + 1) * yOffset);
e.Graphics.FillEllipse(Brushes.Black,
dot.X - sizeOfDot / 2, dot.Y - sizeOfDot / 2,
sizeOfDot, sizeOfDot);
}
PointF dot1 = new PointF(4 * xOffset, 2 * yOffset);
PointF dot2 = new PointF(2 * xOffset, 3 * yOffset);
e.Graphics.DrawLine(Pens.Black, dot1, dot2);
}
private void Form1_SizeChanged(object sender, EventArgs e)
{
Invalidate();
}
}
---------------------
To connect your dots, you can add something like that at the end of
Form_Paint
:
int[] sequence = new int[] { 1, 2, 3, 4, 12, 11, 19, 20, 21 };
PointF[] points = new PointF[sequence.Length];
for (int i = 0; i < sequence.Length; i++)
points[i] = drawing.Pieces[sequence[i]].Dot;
e.Graphics.DrawLines(Pens.Black, points);