c# - 为字母绘制矩形框

标签 c# system.drawing

我的代码。输出:
enter image description here

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;
我在输出中得到错误的结果,因为我无法获得字母的角并且使用了错误的方式。
但我需要获得正确的字母角像素,绘制矩形并填充它。
像这样:
enter image description here

最佳答案

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

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?

关于c# - 为字母绘制矩形框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69873641/

相关文章:

c# - 如何在桌面上正确绘制矩形错误

c# - 在图像上写文字(指定宽度)

c# - 在 C# 中调整大小和水印图像

c# - 如何使用 Graphics.DrawString 绘制双倍高度文本?

c# - 隐藏(使用 "new"修饰符)接口(interface)方法声明的目的是什么?

c# - GCM ASP.NET Android 教程

c# - Bitmap.LockBits 错误 "Parameter is not valid"当位图是一定大小时?

Mono 上的 C# 位图类具有无效属性

c# - ApiController,Viewmodel和DTO的设计

来自 FormCollection 的 C# LINQ 查询/投影