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

Copying from one picturebox to another when thread ends

我有 2 个图片框,一个来自 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 = ?
}

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

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();
    }

}