直接绘制到PictureBox

本文关键字:PictureBox 绘制 | 更新日期: 2023-09-27 18:10:22

我正在开发一个屏幕共享应用程序,它不断运行循环并从套接字接收小帧。下一步是将它们绘制到PictureBox中。当然,我使用thread是因为我不想冻结ui。

这是我的代码:

 Bitmap frame = byteArrayToImage(buff) as Bitmap;//a praticular bitmap im getting from a socket.
 Bitmap current =  (Bitmap)pictureBox1.Image;
 var graphics = Graphics.FromImage(current);
 graphics.DrawImage(frame, left, top);//left and top are two int variables of course.
 pictureBox1.Image = current;

但是现在我得到一个错误:

对象已经在其他地方被使用。

var graphics = Graphics.FromImage(current);

trying to Clone it, Create a New Bitmap(current)

直接绘制到PictureBox

无效()你的PictureBox,使它重新绘制自己:

Bitmap frame = byteArrayToImage(buff) as Bitmap;
using (var graphics = Graphics.FromImage(pictureBox1.Image))
{
    graphics.DrawImage(frame, left, top);
}
pictureBox1.Invalidate();

如果你需要它是线程安全的,那么:

pictureBox1.Invoke((MethodInvoker)delegate {
    Bitmap frame = byteArrayToImage(buff) as Bitmap;
    using (var graphics = Graphics.FromImage(pictureBox1.Image))
    {
        graphics.DrawImage(frame, left, top);
    }
    pictureBox1.Invalidate();
});