【问题标题】:Draw border around bitmap在位图周围绘制边框
【发布时间】:2012-11-13 07:48:28
【问题描述】:

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

宽度固定,高度可变。

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

这将如何工作?

【问题讨论】:

  • 我想创建一个位图宽度 +40 像素和高度 +40 像素的图形对象(每边 20 像素)。我设置了白色背景并在中间添加了位图,但我真的不知道该怎么做......
  • 然后……你试过了吗?或者至少开始为此编写代码?

标签: c# graphics bitmap compact-framework


【解决方案1】:

您可以在位图后面画一个矩形。矩形的宽度为 (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。我就是这样做的,但 OP 可能需要一些代码来确定答案。
【解决方案2】:

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

【讨论】:

  • 这种方法对位图有破坏性,并且只适用于嵌入边框(虽然我同意,但我的方法只适用于起始边框)。
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2021-11-08
    • 1970-01-01
    • 2015-01-10
    • 2020-10-15
    • 1970-01-01
    相关资源
    最近更新 更多