Draw border around bitmap

后端 未结 3 1448
天涯浪人
天涯浪人 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;
    }
    
    0 讨论(0)
  • 2021-01-12 21:35

    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);
    }
    
    0 讨论(0)
  • 2021-01-12 21:38

    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));
    
    0 讨论(0)
提交回复
热议问题