【问题标题】:Draw rectangle box for letters为字母绘制矩形框
【发布时间】:2021-12-20 17:06:17
【问题描述】:

我的代码。输出:

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;

我在输出中得到了错误的结果,因为我无法得到字母的角并且使用了错误的方式。

但我需要得到正确的字母角像素,绘制矩形并填充它。 像这样:

【问题讨论】:

  • a) 并非所有字符都具有相同的宽度。除了测量整个字符串之外,您可能还需要测量每个字符。b) 在计算 w 时,您会松动一点,而相乘时会更多。暂时使用浮动。 c) 最后尝试均匀分布空白区域..

标签: c# system.drawing


【解决方案1】:

这一行让我在你的代码中发现了一个错误:

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 个不同的字母。

一种解决方案是使用monospaced 字体绘制字母。

或者,如果您不想要等宽字体,请查看How to measure width of character precisely?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    相关资源
    最近更新 更多