在位图周围绘制边框

时间:2012-11-13 07:48:29

标签: c# graphics bitmap compact-framework

我的代码中有System.Drawing.Bitmap

宽度固定,高度变化。

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

这将如何运作?

3 个答案:

答案 0 :(得分:6)

您可以在位图后面绘制一个矩形。矩形的宽度为(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);
}

答案 1 :(得分:6)

您可以使用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));

答案 2 :(得分:0)

以下功能将在位图图像周围添加边框。原始图像的大小会随着边框的宽度而增加。

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;
}