2015-08-30 40 views
0

我開發了一個屏幕共享應用程序,它不斷運行一個循環,並從套接字接收一個小幀。然後下一步就是將它們繪製到picturebox中。 當然,我使用線程,因爲我不想凍結用戶界面。直接畫到圖片框

這是我的代碼:

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; 

但我現在得到一個錯誤:

Object is already in use elsewhere.

在這一行var graphics = Graphics.FromImage(current);

試過Clone,創建一個New Bitmap(current) ..仍然沒有成功..

+1

您從映像中創建一個圖形上下文,這並沒有直接引用您的圖像更多內容在這個圖片框裏,它只是圖片的一個新版本。之後您必須再次將圖像設置到圖片框中 – Icepickle

+1

實際上,您正在操縱「pictureBox1」圖片的實例(或者您的意思是「直接引用」,Icepickle?)。唯一的問題是'pictureBox1'根本不知道你對它的'Image'所做的修改 - 所以它不會重繪。嘗試調用'pictureBox1.Refresh()'或'pictureBox1.Invalidate()'(以下Icepickle的建議:'pictureBox1.Image = pictureBox1.Image;'應該也可以 - 自己決定) – olydis

+1

呃?...我同意olydis。只需刷新你的picturebox,它應該更新! –

回答

0

Invalidate()your圖片框所以重繪自己:

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

我只是試圖無效,但它非常非常非常緩慢,並使整個繪圖過程變得緩慢..請參閱我剛剛編輯它的問題中的最後一行。現在,我將新圖像分配給圖片框控件,但即時圖片仍然有一點興趣。謝謝 !! – Slashy

+0

請注意,在我的示例中,有一個「使用」塊來正確處理圖形。這應該消除你看到的錯誤。 –

+0

請再次查看帖子。只是編輯它。謝謝你的一切! – Slashy