2014-10-04 80 views
1

在pictureBox1油漆事件,我試圖繪製圍繞圖像的矩形中pictureBox1:如何在pictureBox1邊框周圍畫一個矩形?

private void pictureBox1_Paint(object sender, PaintEventArgs e) 
     {   
       e.Graphics.DrawRectangle(new Pen(Brushes.Red, 5), new Rectangle(0, 0, pictureBox1.Image.Width, 
        pictureBox1.Image.Height));   
     } 

但我得到的是這樣的:

Rectangle around image

,我也試着畫矩形aorund the pictureBox1它自己:

private void pictureBox1_Paint(object sender, PaintEventArgs e) 
     { 
      e.Graphics.DrawRectangle(Pens.Green, 0, 0 
            , pictureBox1.Width, pictureBox1.Height); 
     } 

但在這種情況下,我得到一個濃密的綠線o只有左側,頂部右側和底部沒有綠色。

Rectangle around pictureBox

在desinger的pictureBox1它的屬性SizeMode設置爲StretchImage 怎樣繪製在這兩種情況下的矩形?

以及如何調用頂線的屬性?這不是高度也許是頂部?如果我想只在pictureBox的頂部找到並繪圖,它是如何調用的?

+2

使用第二個代碼示例,但使用-1或更小來減少矩形的寬度和高度位置。 'e.Graphics.DrawRectangle(Pens.Green,0,0 ,pictureBox1.Width - 1,pictureBox1.Height - 1);' – Measuring 2014-10-04 19:32:57

回答

1

裏面PictureBox的畫很容易:

private void pictureBox1_Paint(object sender, PaintEventArgs e) 
{ 
    float penWidth = 5F; 
    Pen myPen = new Pen (Brushes.Red, (int)penWidth); 
    e.Graphics.DrawRectangle(myPen, penWidth/2F, penWidth/2F, 
          (float)pictureBox1.Width - 2F * penWidth, 
          (float)pictureBox1.Height - 2F * penWidth); 

    myPen.Dispose(); 
} 

爲了吸引外界的PictureBox你需要知道哪些控制是它的下面。例如,如果它是你形式然後用形式繪製

private void Form1_Paint(object sender, PaintEventArgs e) 
{ 
    int lineWidth = 5; 
    Brush myBrush = new SolidBrush (Color.Green); 
    e.Graphics.FillRectangle(myBrush, pictureBox1.Location.X - lineWidth, 
      pictureBox1.Location.Y - lineWidth, pictureBox1.Width + 2 * lineWidth, 
      pictureBox1.Height + 2 * lineWidth); 

    myBrush.Dispose(); 
} 

我使用FillRectangle,因爲這是下的PictureBox的部分是不可見的,這是比較容易控制的寬度。