Draw border around bitmap

后端 未结 3 1473
天涯浪人
天涯浪人 2021-01-12 21:10

I have got a System.Drawing.Bitmap in my code.

The width is fix, the height varies.

What I want to do, is to add a white border around the bitma

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-12 21:32

    Below function will add border around the bitmap image. Original image will increase in size by the width of border.

    private static Bitmap DrawBitmapWithBorder(Bitmap bmp, int borderSize = 10)
    {
        int newWidth = bmp.Width + (borderSize * 2);
        int newHeight = bmp.Height + (borderSize * 2);
    
        Image newImage = new Bitmap(newWidth, newHeight);
        using (Graphics gfx = Graphics.FromImage(newImage))
        {
            using (Brush border = new SolidBrush(Color.White))
            {
                gfx.FillRectangle(border, 0, 0,
                    newWidth, newHeight);
            }
            gfx.DrawImage(bmp, new Rectangle(borderSize, borderSize, bmp.Width, bmp.Height));
    
        }
        return (Bitmap)newImage;
    }
    

提交回复
热议问题