简体   繁体   中英

How to add shape to an existent Picturebox image C#

I have created an Image and I want to add a rectangle around the image and recreate it as Image again to be drawn in a PictureBox but I'm getting out of memory exception

How can I modify the image.

public void Draw(SizeF size)
    {
        int scale = 100;
        Graphics refGraph = this.CreateGraphics();
        IntPtr hdc = refGraph.GetHdc();


        SolidBrush brush = new SolidBrush(Color.Black);
        Pen pen = new Pen(Color.Black, 4);
        try
        {
            Metafile image = new Metafile(hdc, EmfType.EmfOnly, "Shapes");
            using (Graphics g = Graphics.FromImage(image))
            {
                PointF center = new PointF((float)base.Width / 2, base.Height / 2);

                //Draw a rect
                RectangleF Block = new RectangleF(new PointF(center.X - size.Width * scale / 2, center.Y - size.Height * scale / 2), new SizeF(size.Width * scale, size.Height * scale));
                g.FillRectangle(brush, Block);
          }
            //Image = image;
            ModifyImage(image);
        }
        finally
        {
            refGraph.ReleaseHdc(hdc);
            refGraph.Dispose();
            pen.Dispose();
            brush.Dispose();
        }

        Invalidate();
    }

    public void ModifyImage(Metafile image)
    {
        Graphics g = Graphics.FromImage(image);
            PointF center = new PointF((float)Image.Width / 2, Image.Height / 2);
            int bufferAmount = 5;
            g.DrawRectangle(Pens.White, center.X - (Image.Width + bufferAmount) / 2, center.Y - (Image.Height + bufferAmount) / 2, Image.Width + bufferAmount, Image.Height + bufferAmount);

        pictureBox.Image = image;
    }

Thanks

You can create a Graphics from the image using the FromImage method, then use Graphics drawing methods to draw whatever you like. Here is a code sample:

System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(yourImage);

//you may use any pen
graphics.DrawRectangle(System.Drawing.Pens.Blue,0,0,yourImageWidth,yourImageHeight)

yourPictureBox.Image = yourImage;

Create a Graphics object from your image and draw onto it by using a Pen defining the border strength and its color:

using (var gfx = Graphics.FromImage(img))
{
    using (var pen = new Pen(MYCOLOR, 3)
        gfx.DrawRectangle(pen, MYRECT)
}

Note, this will manipulate your source image directly. If you want to have two images, one with and another without a border, you should clone your image before you draw over it:

var imgWithBorder = img.Clone();
// work with imgWithBorder ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM