将图形和图像添加到PictureBox

时间:2015-08-13 09:21:23

标签: c# winforms graphics picturebox

我有一个PictureBox控件。我想在此PictureBox中添加图片。

我这样做了:

pictureBox1.Image = Image.FromFile(@"D:\test.jpg");

我不希望图片填满整个PictureBox

接下来,我想使用以下代码在PictureBox上绘制图形:

Graphics g = pictureBox1.CreateGraphics();

g.DrawArc(....);
g.DrawLine(....);

它应该是如下图所示:

enter image description here

在上图中,图像应仅在蓝色矩形的边界内,我想在其周围绘制图形。如何绘制图像?

1 个答案:

答案 0 :(得分:2)

您可以使用Paint事件或创建Graphics对象,然后绘制圆和线,如下所示:
示例代码段:

   private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawLine(
            new Pen(Color.Red,2f), 
            new Point(0,0), 
            new Point(pictureBox1.Size.Width, pictureBox1.Size.Height ));

        e.Graphics.DrawEllipse(
            new Pen(Color.Red, 2f),
            0,0, pictureBox1.Size.Width, pictureBox1.Size.Height  );
    }

您可以使用以下方法绘制图像:

g.DrawImage(image, new Rectangle(10, 10, 200, 200));

参考这些主题:
how to draw drawings in picture box
How do I draw a circle and line in the picturebox?
Drawing on picture box images
FAQ: How do I draw an image respectively on the PictureBox control and Image object?