代码之家  ›  专栏  ›  技术社区  ›  Slashy

直接绘制到PictureBox

  •  0
  • Slashy  · 技术社区  · 9 年前

    我正在开发一个 屏幕共享应用 其不断地运行循环并从套接字接收小帧。下一步是将他们纳入 图片框 . 当然,我使用线程是因为我不想冻结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);

    已尝试 Clone 它,创建 New Bitmap(current) .仍然没有成功。

    1 回复  |  直到 9 年前
        1
  •  0
  •   Idle_Mind    9 年前

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