在刷新/无效时保持在面板上绘制的东西

时间:2015-03-09 08:27:13

标签: c# graphics panel paint

问题很简单。有没有办法在每次Paint事件触发时都使用Graphics保持在面板上绘制的东西?

在一个简单的程序上演示:每隔100毫秒打开面板上的一个随机像素,直到面板全部着色。

1 个答案:

答案 0 :(得分:1)

简短的例子:

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
    }
}