簡體   English   中英

為字母繪制矩形框

[英]Draw rectangle box for letters

我的代碼。 輸出: 在此處輸入圖片說明

Bitmap bitmap = new Bitmap(600, 300, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
GraphicsPath path = new GraphicsPath();
StringFormat format = new StringFormat();
Rectangle rect = new Rectangle(0, 0, 600, 300);
SolidBrush Brush = new SolidBrush(Color.White);
g.FillRectangle(Brush, rect);


g.SmoothingMode = SmoothingMode.AntiAlias;
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
path.AddString(textBox1.Text, FontFamily.GenericSansSerif, (int)FontStyle.Bold, 128, rect, format);

Brush = new SolidBrush(Color.Blue);
g.FillPath(Brush, path);

float x = path.GetBounds().X;
float y = path.GetBounds().Y;
float w = path.GetBounds().Width / textBox1.Text.Length;
float h = path.GetBounds().Height;

Pen redPen = new Pen(Color.Red, 2);
for (int i = 0; i < textBox1.Text.Length+1; i++)
{
    rect = new Rectangle((int)x, (int)y, (int)w*i, (int)h);
    g.DrawRectangle(redPen, rect);
}

pictureBox1.Image = bitmap;

我在輸出中得到錯誤的結果,因為我無法獲得字母的角並且使用了錯誤的方式。

但我需要獲得正確的字母角像素,繪制矩形並填充它。 像這樣: 在此處輸入圖片說明

這一行讓我在你的代碼中發現了一個錯誤:

for (int i = 0; i < textBox1.Text.Length+1; i++)

它應該是:

for (int i = 0; i < textBox1.Text.Length; i++)

但隨后確實似乎只出現了 3 個紅色框。

原因是第一個矩形(帶有您的代碼)非常小,因為寬度是(int)w*i 那應該是(int)w*(i+1)

現在回到你繪制矩形的地方。

如果您使用文本“WWWW”,您會發現您的解決方案看起來還不錯。

但是如果你用'IIII'測試,十你應該注意到最左邊的'I'在紅框中左對齊,最右邊的'I'在紅框中右對齊。

您正在繪制 4 個相等的框,用不同的 4 個字母圍成一圈。

解決方案可能是使用等寬字體繪制字母。

或者,如果您不想要等寬字體,請查看如何精確測量字符寬度?

暫無
暫無

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

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