0

The question is fairly simple. Is there a way to keep the things drawn on a panel with Graphics everytime the Paint event fires?

Demonstrated on a simple program: Turn on a random pixel on the panel every 100 miliseconds until the panel is all colored.

HajdaCZ
  • 73
  • 13
  • 1
    Use a bitmap image and use your draw functions on the bitmap, in the paint event draw the bitmap to the panel. – Florian Schmidinger Mar 09 '15 at 08:50
  • What's a better method? Drawing the bitmap using Graphics or setting it as a panel background? – HajdaCZ Mar 09 '15 at 08:56
  • 1
    It depends on the situation. If the graphics are changing use the surface if they only build up use the bitmap. you may want to [read this](http://stackoverflow.com/questions/28830821/preserve-painting-after-resize-or-refresh/28834298?s=9|0.1112#28834298).. – TaW Mar 09 '15 at 09:09

1 Answers1

1

Short example:

public partial class Form1 : Form
{
    private Bitmap bitmap;
    private Random random = new Random();

    public Form1()
    {
        InitializeComponent();
        bitmap = new Bitmap(panel1.Width,panel1.Height);
    }

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawImage(bitmap,new Point(0,0));
    }

    private void button1_Click(object sender, EventArgs e)
    {
        using (Graphics graphics = Graphics.FromImage(bitmap))
        {

            graphics.DrawLine(
                new Pen(new SolidBrush(Color.Black),1),
                new Point(random.Next(0, bitmap.Width), random.Next(0, bitmap.Width)),
                new Point(random.Next(0, bitmap.Width), random.Next(0, bitmap.Width)));

        }
        panel1.Invalidate(); // redraw
    }
}
Florian Schmidinger
  • 4,682
  • 2
  • 16
  • 28