如何在不填充的情况下获取绘制字符串的尺寸?
我正在尝试创建一个带有一些文本的图像,并且我希望图像的大小与渲染文本的大小相匹配。
当我使用 System.Windows.Forms.TextRenderer.MeasureText(...) 测量文本时,我得到包含字体填充的尺寸。当渲染文本时,它似乎使用相同的填充。
有什么方法可以确定文本字符串的大小,然后在没有任何填充的情况下渲染它?
这是我尝试过的代码:
// Measure the text dimensions
var text = "Hello World";
var fontFamily = new Font("Arial", 30, FontStyle.Regular);
var textColor = new SolidBrush(Color.Black);
Size textSize = TextRenderer.MeasureText(text, fontFamily,
Size.Empty, TextFormatFlags.NoPadding);
// Render the text with the given dimensions
Bitmap bmp = new Bitmap(textSize.Width, textSize.Height);
Graphics g = Graphics.FromImage(bmp);
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.DrawString(text, fontFamily, textColor, new PointF(0, 0));
bmp.Save("output.png", ImageFormat.Png);
这是当前渲染出来的代码:
这是我想要渲染的内容:
我还研究了 Graphics.MeasureString(...)
,但这只能用于现有的Graphics
对象。我想在创建图像之前知道尺寸。另外,调用 Graphics.MeasureString(...)
返回相同的尺寸,因此它对我没有任何帮助。
I'm trying to create an image with some text on it and I want the image's size to match the size of the rendered text.
When I use System.Windows.Forms.TextRenderer.MeasureText(...)
to measure the text, I get dimensions that include font padding. When the text is rendered, it seems to use the same padding.
Is there any way to determine the size of a string of text and then render it without any padding?
This is the code I've tried:
// Measure the text dimensions
var text = "Hello World";
var fontFamily = new Font("Arial", 30, FontStyle.Regular);
var textColor = new SolidBrush(Color.Black);
Size textSize = TextRenderer.MeasureText(text, fontFamily,
Size.Empty, TextFormatFlags.NoPadding);
// Render the text with the given dimensions
Bitmap bmp = new Bitmap(textSize.Width, textSize.Height);
Graphics g = Graphics.FromImage(bmp);
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.DrawString(text, fontFamily, textColor, new PointF(0, 0));
bmp.Save("output.png", ImageFormat.Png);
This is what currently gets rendered out:
This is what I want to render:
I also looked into Graphics.MeasureString(...)
, but that can only be used on an existing Graphics
object. I want to know the size before creating the image. Also, calling Graphics.MeasureString(...)
returns the same dimensions, so it doesn't help me any.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这是因为 30 点字体的字体高度为 46。
这样您就可以拥有特殊的大写字符 (ÉÖÄÅ) 和情人大小写字符 (gqp)。
前导和尾随空格可能也与此有关。
I think it is because the font height is 46 for 30point font.
This is so you can have special uppercase characters (ÉÖÄÅ) and lover case characters(gqp).
The leading and trailing blank spaces probably also have some thing to do with this.