Reputation: 77
I have 2 pictureboxes, one from UI (let's call is PB1) and another instanced during DrawingFunction (call it PB2).
Since DrawingFunction is a longrun operation I decided to create this PB2 and draw on it via Graphics by BackgroundWorker. When backgroundworker finishes it should copy PB2 contents to PB1 so UI does not freezes during DrawingFunction operation. How can I do it?
Code snippet:
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 = ?
}
Upvotes: 1
Views: 148
Reputation: 28499
Do not use a PictureBox to create the image in the BackgroundWorker but a Bitmap. You can then simply assign that Bitmap to the Image property of the Picture Box.
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();
}
}
Upvotes: 2