字符串是“Hello World”,最后有 10 个空格字符,但是 右对齐 中的 Graphics.DrawString 省略了所有空格字符,它只绘制了“Hello World”。
protected override void OnPaint(PaintEventArgs e)
{
Rectangle rct = new Rectangle(20, 100, 200, 20);
e.Graphics.DrawRectangle(new Pen(Color.Lime), rct);
e.Graphics.DrawString("Hello World ", Font, new SolidBrush(SystemColors.ControlText), rct, new StringFormat() { Alignment = StringAlignment.Far});
base.OnPaint(e);
}
最佳答案
在使用 Gdi+ 绘制字符串时包含尾随空格 Graphics.DrawString
方法,传递一个 StringFormat
适当重载并添加或附加 (|=
) StringFormatFlags.MeasureTrailingSpaces
StringFormat.FormatFlags
的值属性(property)。
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Rectangle rct = new Rectangle(20, 100, 200, 20);
string s = "Hello World ";
using (var sf = new StringFormat(StringFormat.GenericTypographic))
{
sf.Alignment = StringAlignment.Far;
sf.LineAlignment = StringAlignment.Center;
sf.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
e.Graphics.DrawString(s, Font, SystemBrushes.ControlText, rct, sf);
}
e.Graphics.DrawRectangle(Pens.Lime, rct);
}
考虑使用 Gdi TextRenderer
类在控件上绘制字符串,除非遇到类似 drawing on transparent backgrounds 的问题.
之前的代码可以这样写:
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Rectangle rct = new Rectangle(20, 100, 200, 20);
string s = "Hello World ";
TextRenderer.DrawText(e.Graphics, s, Font, rct, SystemColors.ControlText,
TextFormatFlags.Right |
TextFormatFlags.VerticalCenter);
e.Graphics.DrawRectangle(Pens.Lime, rct);
}
关于c# - Graphics.DrawString 不绘制最后一个 SPACE 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74653444/