我从this messageboard post 获得了一些对我很有效的代码。在我自己的一些摆弄之后,我最终得到的是以下内容:
public System.Drawing.SizeF MeasureString(string Message, DXFonts.DXFont Font, float Width, ContentAlignment Align)
{
SharpDX.DirectWrite.TextFormat textFormat = Font.GetFormat(Align);
SharpDX.DirectWrite.TextLayout layout =
new SharpDX.DirectWrite.TextLayout(DXManager.WriteFactory, Message, textFormat, Width, textFormat.FontSize);
return new System.Drawing.SizeF(layout.Metrics.Width, layout.Metrics.Height);
}
如果您插入文本、字体、建议的宽度和对齐方式,它会导出一个矩形的大小来保存文本。当然,您要查找的是高度,但这包括宽度,因为文本很少会填满整个空间。
注意:根据评论者的建议,代码实际上应该是以下资源的 Dispose():
public System.Drawing.SizeF MeasureString(string Message, DXFonts.DXFont Font, float Width, ContentAlignment Align)
{
SharpDX.DirectWrite.TextFormat textFormat = Font.GetFormat(Align);
SharpDX.DirectWrite.TextLayout layout =
new SharpDX.DirectWrite.TextLayout(DXManager.WriteFactory, Message, textFormat, Width, textFormat.FontSize);
textFormat.Dispose(); // IMPORTANT! If you don't dispose your SharpDX resources, your program will crash after a while.
return new System.Drawing.SizeF(layout.Metrics.Width, layout.Metrics.Height);
}