gpt4 book ai didi

c# - GDI+,从图形 DrawString() 中删除空格

转载 作者:太空狗 更新时间:2023-10-30 01:17:49 25 4
gpt4 key购买 nike

我在使用 C# GDI+ 绘制字符串函数时遇到问题——我无法获得绘制字符串的确切大小——没有内部前导和外部前导,只有 em 高度。 Microsoft 提供的字体/字符串测量 API 似乎总是输出一个比文本绘图大几个像素的边界框,即使在我删除了内部行距之后也是如此。

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.Clear(Color.Black);
String text = "The quick brown fox jumps over the lazy dog";
Font font = new System.Drawing.Font(FontFamily.GenericSerif, 24);
float internalLeading = font.Size * (font.FontFamily.GetCellAscent(font.Style) + font.FontFamily.GetCellDescent(font.Style) - font.FontFamily.GetEmHeight(font.Style)) / font.FontFamily.GetEmHeight(font.Style);
StringFormat format = StringFormat.GenericTypographic;
format.Trimming = StringTrimming.None;
format.FormatFlags = StringFormatFlags.NoWrap;
System.Drawing.RectangleF rect = new System.Drawing.RectangleF(0, 0, pictureBox1.Width,pictureBox1.Height);
System.Drawing.CharacterRange[] ranges = { new System.Drawing.CharacterRange(0, text.Length) };
System.Drawing.Region[] boundings = new System.Drawing.Region[1];
format.SetMeasurableCharacterRanges(ranges);
boundings = g.MeasureCharacterRanges(text, font, rect, format);
rect = boundings[0].GetBounds(g);
g.DrawString(text, font, new SolidBrush(Color.Red), new RectangleF(0,0,rect.Width,rect.Height), format);
g.DrawRectangle(Pens.Yellow, rect.X, rect.Y + internalLeading, rect.Width, rect.Height - internalLeading);
}

输出如下所示。我们可以看到文本和边界框的上边缘之间仍然有一些像素。

enter image description here

我可以通过读取图像中的像素并自己计算边界框来获得绘制字符串的确切大小。但它很慢。我能知道是否有一种简单的方法可以解决这个问题吗?

最佳答案

GDI+ 处理的不仅仅是英语,而且行高是固定的(想象一下,如果每一行都是该行文本的高度,那会是多么恐怖)。

边界框还考虑了可以修饰这些字符的各种变音符号,包括英语中的类似内容,例如 COÖPERATE

参见:

Diaresis and diacritis

请注意分音符 (¨) 几乎不适合边界框,而 ˇ 很明显在边界框之外 - 然而,在底部,有足够的空间适合 q。是什么赋予了?好吧,MeasureString 用于文本格式化,而不是用于获取可以呈现文本的最小可能矩形 - 当然,这会因不应改变文本对齐方式的事情而进一步复杂化,例如使用 ClearType。

该函数是基于这样的假设构建的,即您非常喜欢具有相同高度的行 - 这就是所有文本通常呈现的方式。

直接引用MSDN:

The MeasureString method is designed for use with individual strings and includes a small amount of extra space before and after the string to allow for overhanging glyphs. Also, the DrawString method adjusts glyph points to optimize display quality and might display a string narrower than reported by MeasureString.

关于c# - GDI+,从图形 DrawString() 中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30317408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com