在WinForms应用程序中,我试图测量要绘制的某些文本的大小,而没有填充。这是我最近得到的...
protected override void OnPaint(PaintEventArgs e) {
DrawIt(e.Graphics);
}
private void DrawIt(Graphics graphics) {
var text = "123";
var font = new Font("Arial", 32);
var proposedSize = new Size(int.MaxValue, int.MaxValue);
var measuredSize = TextRenderer.MeasureText(graphics, text, font, proposedSize, TextFormatFlags.NoPadding);
var rect = new Rectangle(100, 100, measuredSize.Width, measuredSize.Height);
graphics.DrawRectangle(Pens.Blue, rect);
TextRenderer.DrawText(graphics, text, font, rect, Color.Black, TextFormatFlags.NoPadding);
}
...但是从结果中可以看到...
...仍然有大量填充,特别是在顶部和底部。有什么方法可以测量绘制字符的实际边界(确实很糟糕,例如打印到图像然后寻找绘制的像素)?
谢谢。
答案 0 :(得分:2)
(我将这个答案标记为“ the”答案,以便人们知道它已经被回答了,但是@TaW实际上提供了解决方案-请参阅上面的链接。)
@TaW-这就是窍门。我仍在努力使文字到达我想要的位置,但我实在是太过困难了。这是我最后得到的代码...
protected override void OnPaint(PaintEventArgs e) {
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
DrawIt(e.Graphics);
}
private void DrawIt(Graphics graphics) {
var text = "123";
var font = new Font("Arial", 40);
// Build a path containing the text in the desired font, and get its bounds.
GraphicsPath path = new GraphicsPath();
path.AddString(text, font.FontFamily, (int)font.Style, font.SizeInPoints, new Point(0, 0), StringFormat.GenericDefault);
var bounds = path.GetBounds();
// Move it where I want it.
var xlate = new Matrix();
xlate.Translate(100, 100);
path.Transform(xlate);
// Draw the path (and a bounding rectangle).
graphics.DrawPath(Pens.Black, path);
bounds = path.GetBounds();
graphics.DrawRectangle(Pens.Blue, bounds.Left, bounds.Top, bounds.Width, bounds.Height);
}
...这是结果(请注意漂亮的紧边框)...
答案 1 :(得分:0)
您尝试过
Graphics.MeasureString("myString", myFont, int.MaxValue, StringFormat.GenericTypographic)