我正在嘗試在中心的 850x610 空白位圖中插入 800x500 的影像。內部影像應位于中心,頂部還有一個標題。我附上一張圖片來說明我的想法:
public static Bitmap AddBorder(Bitmap srcImage)
{
Bitmap bmp = new Bitmap(srcImage.Width 45, srcImage.Height 100);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(srcImage, 0, 0);
g.DrawImage(srcImage, new Rectangle(bmp.Width - 1, 0, 1, bmp.Height));
g.DrawImage(srcImage, new Rectangle(0, bmp.Height - 1, bmp.Width, 1));
return bmp;
}
我嘗試使用 drawRectangle、drawImage 等來繪制它。但是,我無法正確填充它,如上圖所示。我也無法將邊框添加到內部影像。我想知道如何做到這一點。
uj5u.com熱心網友回復:
下面的示例設定了新的位圖大小,它用背景(黑色)填充它,在中心繪制影像,最后在測量文本后將它在中心對齊(僅限寬度檢查)。
public static Bitmap AddBorder(Bitmap srcImage, string text)
{
Bitmap bmp = new Bitmap(850, 610);
using(Graphics g = Graphics.FromImage(bmp))
{
// Background
g.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height));
// Source Image
Rectangle rect = new Rectangle(25, 55, 800, 500);
g.DrawImage(srcImage, rect);
// Border
int borderThickness = 2;
using(Pen pen = new System.Drawing.Pen(Brushes.Black, borderThickness))
{
pen.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset;
g.DrawRectangle(pen, new Rectangle(rect.X - borderThickness, rect.Y - borderThickness, rect.Width borderThickness, rect.Height borderThickness));
}
// Text String
using (Font font = new Font("Arial", 16))
{
SizeF size = g.MeasureString(text, font);
g.DrawString(text, font, Brushes.Black, new PointF((bmp.Width / 2) - (size.Width / 2), rect.Top - (size.Height borderThickness)));
}
}
return bmp;
}
根據評論更新(在居中影像上方添加文字)!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/498406.html
標籤:C#
上一篇:WPF-GridRows間距混淆