如何围绕pictureBox1边框绘制一个矩形?

时间:2014-10-04 19:21:00

标签: c# .net winforms

在pictureBox1 paint事件中,我试图在pictureBox1中的Image周围绘制一个矩形:

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 it self:

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

但在这种情况下,我只在左边和右边和底部的绿色线上没有绿色。

Rectangle around pictureBox

desinger中的pictureBox1它的属性SizeMode设置为StretchImage 如何在两种情况下绘制矩形?

我称之为顶线的属性如何?它不是高度可能顶级?如果我想在pictureBox的顶部找到并绘制它是如何调用的?

1 个答案:

答案 0 :(得分:2)

要绘制内部图片框很简单:

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

要绘制外部图片框,您需要知道它下面有哪个控件。例如,如果它是您的表单,那么使用表单颜色

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 下的部分不可见,并且更容易控制宽度。