线程结束时从一个图片框复制到另一个图片框

时间:2016-03-10 13:08:43

标签: c# winforms backgroundworker picturebox

我有两个图片盒,一个来自UI(让我们称之为PB1),另一个是在DrawingFunction(称为PB2)中实例化。

由于DrawingFunction是一个长期操作,我决定创建这个PB2并通过BackgroundWorker的Graphics绘制它。当backgroundworker完成后,它应该将PB2内容复制到PB1,这样UI在DrawingFunction操作期间不会冻结。我该怎么办?

代码段:

PictureBox PB2 = new PictureBox();

public PictureBox Draw(int width, int height)
{
    PictureBox picbox = new PictureBox();
    picbox.Width = width;
    picbox.Height = height;

    Graphics G = picbox.CreateGraphics();
    G.DrawRectangle(...);

    return picbox;

}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    PB2 = Draw(PB1.Width, PB1.Height);
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    PB1 = ?
}

1 个答案:

答案 0 :(得分:2)

不要使用PictureBox在BackgroundWorker中创建图像,而是使用位图。然后,您可以简单地将该位图分配给图片框的Image属性。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public Bitmap Draw(int width, int height)
    {
        Bitmap myBitmap = new Bitmap(width, height);

        using (var graphics = Graphics.FromImage(myBitmap))
        {
            graphics.DrawRectangle(new Pen(Color.Red), new Rectangle(2,2,20,20));
        }

        return myBitmap;
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        e.Result = Draw(PB1.Width, PB1.Height);
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        PB1.Image = e.Result as Bitmap;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }

}