Я хочу нарисовать сетку на изображении в PictureBox.
Но, когда сетка нарисована, изображение исчезает.
Как я могу исправить этот код?Он рисует сетку, когда флажок установлен или я изменяю размер сетки с помощью трекбара.
private void grid()
{
int x, y;
int w = pictureBox1.Size.Width;
int h = pictureBox1.Size.Height;
int inc = trackBar1.Value;
BackImage = new Bitmap(w, h);
Pen myPen = new Pen(Color.Green);
Graphics gr = Graphics.FromImage(BackImage);
gr.Clear(SystemColors.Control);
if (checkBox1.Checked == true)
{
myPen.Color = Color.Green;
for (x = 0; x < w; x += inc)
gr.DrawLine(myPen, x, pictureBox1.Location.Y, x, h);
for (y = 0; y < h; y += inc)
gr.DrawLine(myPen, pictureBox1.Location.X, y, w, y);
}
Invalidate();
myPen.Dispose();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
grid();
Refresh();
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
grid();
Refresh();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (BackImage != null)
e.Graphics.DrawImage(BackImage, 0, 0);
}