Draw border around bitmap

混江龙づ霸主 提交于 2019-12-01 07:39:34

You could draw a rectangle behind the bitmap. The width of the rectangle would be (Bitmap.Width + BorderWidth * 2), and the position would be (Bitmap.Position - new Point(BorderWidth, BorderWidth)). Or at least that's the way I'd go about it.

EDIT: Here is some actual source code explaining how to implement it (if you were to have a dedicated method to draw an image):

private void DrawBitmapWithBorder(Bitmap bmp, Point pos, Graphics g) {
    const int borderSize = 20;

    using (Brush border = new SolidBrush(Color.White /* Change it to whichever color you want. */)) {
        g.FillRectangle(border, pos.X - borderSize, pos.Y - borderSize, 
            bmp.Width + borderSize, bmp.Height + borderSize);
    }

    g.DrawImage(bmp, pos);
}

You can use 'SetPixel' method of a Bitmap class, to set nesessary pixels with the color. But more convenient is to use 'Graphics' class, as shown below:

            bmp = new Bitmap(FileName);
            //bmp = new Bitmap(bmp, new System.Drawing.Size(40, 40));

            System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);

            gr.DrawLine(new Pen(Brushes.White, 20), new Point(0, 0), new Point(0, 40));
            gr.DrawLine(new Pen(Brushes.White, 20), new Point(0, 0), new Point(40, 0));
            gr.DrawLine(new Pen(Brushes.White, 20), new Point(0, 40), new Point(40, 40));
            gr.DrawLine(new Pen(Brushes.White, 20), new Point(40, 0), new Point(40, 40));

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!