关于C#:在GDI中在画布上绘制图像时,如何获取Words的长度和高度

How to get Words length and height, when drawing the images on a canvas in GDI+

我在C中使用GDI在画布上绘制字符串。
是否有任何API可以获取某种字体的字符串的外层(宽度,高度)?
非常感谢!
非常感谢Windows程序员的解决方案。
我编写了以下代码。

1
2
3
4
5
6
7
    Bitmap bitmap(1000,1000);
    Graphics graphics(&bitmap);
    RectF rec;
    RectF useless;
    graphics.MeasureString(m_sWords, -1, m_pFont.get(), useless, &rec);
    int WordWidth = rec.Width + 1;
    int WordHeight Height = rec.Height + 1;

需要使用真实的图形来调用MeasureString吗?有什么方法可以在不创建大型Graphics实例的情况下获得wordwidth,wordheight?我发现这是资源消耗。


Graphics :: MeasureString计算一个近似值。


要使图片完整:只需使用GraphicsPath即可,这样做更好,因为它不需要DeviceContext:

1
2
3
4
5
6
7
8
9
10
11
Dim p As New GraphicsPath

Using stringFormat As New StringFormat()
    stringFormat.Trimming = StringTrimming.EllipsisCharacter
    stringFormat.LineAlignment = StringAlignment.Center
    stringFormat.Alignment = StringAlignment.Near

    p.AddString(text, font.FontFamily, font.Style, font.SizeInPoints, Point.Empty, stringFormat)
End Using

Return p.GetBounds.Size

其中文本是给定的字符串,字体是给定的字体。返回一个SizeF结构。我发现结果比Graphics.MeasureString aka GdipMeasureString-API更精确。


不幸的是,您确实需要使用Graphics对象来执行此操作。

我使用的C#代码(返回RectangleF,因为我想知道宽度和高度)如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/// <summary> The text bounding box. </summary>
private static readonly RectangleF __boundingBox = new RectangleF(29, 25, 90, 40);

/// <summary>
///    Gets the width of a given string, in the given font, with the given
///    <see cref="StringFormat"/> options.
/// </summary>
/// <param name="text">The string to measure.</param>
/// <param name="font">The <see cref="Font"/> to use.</param>
/// <param name="fmt">The <see cref="StringFormat"/> to use.</param>
/// <returns> The floating-point width, in pixels. </returns>
private static RectangleF GetStringBounds(string text, Font font,
   StringFormat fmt)
{
   CharacterRange[] range = { new CharacterRange(0, text.Length) };
   StringFormat myFormat = fmt.Clone() as StringFormat;
   myFormat.SetMeasurableCharacterRanges(range);

   using (Graphics g = Graphics.FromImage(
       new Bitmap((int) __boundingBox.Width, (int) __boundingBox.Height)))
   {
      Region[] regions = g.MeasureCharacterRanges(text, font,
         __boundingBox, myFormat);
      return regions[0].GetBounds(g);
   }
}

这将返回整个文本字符串大小的RectangleF,根据指定为__boundingBox的边界框,根据需要将其换行。从好的方面来说,using语句完成后,Graphics对象将被销毁……

顺便说一句,GDI在这方面似乎并不可靠;我发现它有很多错误(例如,请参见我的问题" Graphics.MeasureCharacterRanges在C#.Net中给出错误的尺寸计算?")。如果可以使用System.Windows.Forms中的TextRenderer.DrawText,请使用