簡體   English   中英

在位圖周圍繪制邊框

[英]Draw border around bitmap

我的代碼中有一個System.Drawing.Bitmap

寬度固定,高度變化。

我想要做的是在位圖周圍添加一個白色邊框,大約 20 像素,到所有 4 個邊緣。

這將如何運作?

您可以在位圖后面繪制一個矩形。 矩形的寬度為 (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);
}

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

下面的函數將在位圖圖像周圍添加邊框。 原始圖像的大小將增加邊框的寬度。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM