7

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

宽度是固定的,高度是变化的。

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

这将如何工作?

4

3 回答 3

9

您可以使用 Bitmap 类的 'SetPixel' 方法,用颜色设置必要的像素。但更方便的是使用'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));
于 2012-11-13T08:56:55.383 回答
9

您可以在位图后面绘制一个矩形。矩形的宽度为 (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);
}
于 2012-11-13T08:20:12.720 回答
6

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

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;
}
于 2019-05-08T07:39:20.917 回答