我们正在使用 SharpDX
开发 Windows 8 Metro 应用程序.现在我们必须在 Rectangle
中声明一组字符串.为此,我们尝试使用 SharpDX.DrawingSizeF
找出字体的宽度和高度。 .例如:
Windows.Graphics g;
Model.Font font;
DrawingSizeF size = g.MeasureString(quote, font.Font, new DrawingSizeF(font.Width, font.Height));
我们正在努力找出
MeasureString
不使用 Windows.Graphics
.是否可以?或者还有其他方法可以获取MeasureString
在 SharpDX
或使用 Direct2D
?
最佳答案
我从 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);
}
关于direct2d - sharpDX 中的 MeasureString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12671893/