我有一个包含一些文本和字体的类数组。我想独立于字体大小绘制所有在线对齐的文本。我以为我可以从线条的 Y 位置中减去字体高度,然后在新位置上绘制文本,但这有点困难,因为顶部和底部填充是通过 GDI 添加到文本的。计算工作正常,但文本漂浮在它应该位于的矩形中间的某个位置。我还发现我可以设置 TextFormatFlags
至NoPadding
但这仅有助于左右填充,并且文本仍然漂浮在该行上方。我花了很长时间寻找一种摆脱所有填充的方法,但没有找到任何可以做到这一点的方法。
这是我的代码:
public static void DrawTextOnLine(string text, Font font, Graphics graphics, Color color, int x, int dLineY)
{
float upperY = dLineY - GetFontAscent(font);
Point point = new Point(x, (int)upperY);
TextRenderer.DrawText(graphics, text, font, point, color, TextFormatFlags.NoPadding);
}
有一件事我忘记提及:我也尝试使用 TextFormatFlags
来做到这一点设置为Bottom
。问题是降序字母导致文本位于行上方。
有更简单的方法吗?或者如何删除所有填充?
最佳答案
Link在唐纳德的评论中,他指出了 dar7yl 的出色答案,说得恰到好处。
向 dar7yl 致敬!下面是一个示例和结果,很好地排列在同一行:
private void Form1_Load(object sender, EventArgs e)
{
using (Graphics G = panel2.CreateGraphics() )
{
fonts.Add(new DrawFont(G, new FontFamily("Arial"), 7f));
fonts.Add(new DrawFont(G, new FontFamily("Arial"), 12f));
fonts.Add(new DrawFont(G, new FontFamily("Arial"), 17f));
fonts.Add(new DrawFont(G, new FontFamily("Consolas"), 8f));
fonts.Add(new DrawFont(G, new FontFamily("Consolas"), 10f));
fonts.Add(new DrawFont(G, new FontFamily("Consolas"), 14f));
fonts.Add(new DrawFont(G, new FontFamily("Times"), 9f));
fonts.Add(new DrawFont(G, new FontFamily("Times"), 12f));
fonts.Add(new DrawFont(G, new FontFamily("Times"), 20f));
fonts.Add(new DrawFont(G, new FontFamily("Segoe Print"), 6f));
fonts.Add(new DrawFont(G, new FontFamily("Segoe Print"), 12f));
fonts.Add(new DrawFont(G, new FontFamily("Segoe Print"), 24f));
}
}
List<DrawFont> fonts = new List<DrawFont>();
class DrawFont
{
public Font Font { get; set; }
public float baseLine { get; set; }
public DrawFont(Graphics G, FontFamily FF, float height, FontStyle style)
{
Font = new Font(FF, height, style);
float lineSpace = FF.GetLineSpacing(Font.Style);
float ascent = FF.GetCellAscent(Font.Style);
baseLine = Font.GetHeight(G) * ascent / lineSpace;
}
}
private void panel2_Paint(object sender, PaintEventArgs e)
{
float x = 5f;
foreach ( DrawFont font in fonts )
{
e.Graphics.DrawString("Fy", font.Font, Brushes.DarkSlateBlue, x, 80 - font.baseLine);
x += 50;
}
e.Graphics.DrawLine(Pens.LightSlateGray, 0, 80, 999, 80);
}
我使用Graphics.DrawString
,但TextRenderer
应该也能工作......
关于c# - 如何使用TextRenderer绘制多种尺寸的在线对齐文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29949763/