在位图周围绘制边框

Kar*_*arl 4 c# graphics compact-framework bitmap

System.Drawing.Bitmap我的代码中有一个.

宽度固定,高度变化.

我想要做的是在位图周围添加一个白色边框,大约20个像素,到所有4个边缘.

这怎么样?

Ant*_*nov 8

您可以使用Bitmap类的"SetPixel"方法,使用颜色设置nesessary像素.但更方便的是使用'Graphics'类,如下所示:

            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));
Run Code Online (Sandbox Code Playgroud)


ant*_*ijn 7

您可以在位图后面绘制一个矩形.矩形的宽度为(Bitmap.Width + BorderWidth*2),位置为(Bitmap.Position - new Point(BorderWidth,BorderWidth)).或者至少那是我的方式.

编辑:这是一些实际的源代码,解释了如何实现它(如果你有一个专门的方法来绘制图像):

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);
}
Run Code Online (Sandbox Code Playgroud)

  • +1.这就是我这样做的方式,但OP可能需要一些代码才能解决问题. (2认同)

Bri*_*thi 5

下面的函数将在位图图像周围添加边框。原始图像的大小将增加边框的宽度。

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;
}
Run Code Online (Sandbox Code Playgroud)