2011-11-25 35 views
1

我需要幫助插入一個盒子,我從一個盒子裏畫出來。
這裏是我編碼的筆的代碼,我不知道如何把它放在picturebox中。 將有一個攝像頭運行在picturebox的背景上,我希望我的矩形位於picturebox內。我如何插入一個我從筆中繪製出來的盒子到一個picturebox圖像?

private void button1_Click(object sender, EventArgs e) 
{ 
    if (button1.Text == "Start") 
    { 
     Graphics myGraphics = base.CreateGraphics(); 
     myGraphics.Clear(Color.White); 
     Pen myPen = new Pen(Color.DarkBlue); 
     Rectangle rect = new Rectangle(480, 70, 120, 120); 
     myGraphics.DrawRectangle(myPen, rect); 
     stopWebcam = false; 
     button1.Text = "Stop"; 
    } 
    else 
    { 
     stopWebcam = true; 
     button1.Text = "Start"; 
    } 
} 
+0

要將矩形放入圖片框,請從圖片框(即PictureBox.CreateGraphics())創建圖形。你需要找出合併這兩個圖像的方法。一個從你的網絡攝像頭和矩形 –

+1

除了你不應該做馬克建議,而是應該在OnPaint中執行所有的繪圖。除非你需要知道你在做什麼,否則不要調用CreateGraphics。 –

回答

0

您可能必須將網絡攝像頭圖像繪製到位圖緩衝區並將其用作圖片框的圖像。

這裏是底部例子MSDN頁面:

http://msdn.microsoft.com/en-us/library/system.windows.forms.picturebox.aspx

這是我做這件事的方法。

public void GraphicsToPictureBox (ref PictureBox pb, Graphics graphics, 
           Int32 width, Int32 height) 
{ 
    Bitmap bitmap = new Bitmap(width,height,graphics); 
    pb.Image = bitmap; 
} 
+0

這就是很多的開銷! – Polity

1

在winforms中渲染主要是在OnPaint事件中完成的。您的ButtonClick事件處理程序應該只設置OnPaint的舞臺並可能將其激活。示例:

public class MyForm : Form 
    ... 
    private Rectangle? _boxRectangle; 

    private void OnMyButtonClick(object sender, EventArgs e) 
    { 
     if (button1.Text == "Start") 
     { 
      _boxRectangle = new Rectangle(...); 
      button1.Text = "Stop"; 
     } 
     else 
     { 
      _boxRectangle = null; 
      button1.Text = "Start"; 
     } 
     Invalidate(); // repaint 
    } 

    protected override OnPaint(PaintEventArgs e) 
    { 
     if (_boxRectangle != null) 
     { 
      Graphics g = e.Graphics. 
      Pen pen = new Pen(Color.DarkBlue); 
      g.DrawRectangle(_boxRectangle); 
     } 
    } 
} 
相關問題