2012-11-13 115 views
3

我的代码中有System.Drawing.Bitmap围绕位图绘制边框

宽度固定,高度不等。

我想要做的是在位图周围添加一个白色边框,大约20像素,全部4条边。

这将如何工作?

+0

我认为有关创建的图形与宽度40像素和高度40像素位图(各20侧)的对象。我设置了白色背景,并在中间添加了位图,但是我无法真正弄清楚如何做... – Karl

+0

而且......你试过了吗?或者至少开始为此编写代码? – LightStriker

回答

5

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

+1。这就是我要这么做的方式,但OP可能需要一些代码才能收回答案。 – jp2code

3

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

但是,此方法对位图具有破坏性,只适用于插入边框(尽管我会授予它,但我的方法仅适用于起始边框)。 – antonijn

+0

是的,你是对的。我没有考虑过位图 –