我们正在使用SharpDX
开发Windows8 metro应用程序。现在我们必须在Rectangle
中声明一组字符串集。为此,我们尝试使用SharpDX.DrawingSizeF
找出字体的宽度和高度。例如:
Windows.Graphics g;
Model.Font font;
DrawingSizeF size = g.MeasureString(quote, font.Font, new DrawingSizeF(font.Width, font.Height));
我们正在尝试找出不使用Windows.Graphics
的MeasureString
。有可能吗?或者,有没有其他方法可以在SharpDX
中或使用Direct2D
获取MeasureString
发布于 2017-03-07 23:26:53
我从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);
}
如果您插入文本、字体、建议的宽度和对齐方式,它将导出一个矩形的大小以容纳文本。当然,您需要的是高度,但这包括宽度,因为文本很少填满整个空间。
注意:按照评论者的建议,实际上应该是以下代码来处置资源:
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);
}
发布于 2018-12-01 21:08:14
我修改了第一个答案,以解决在VB.net中无法访问DXFont的限制:
Public Function MeasureString(Message As String, textFormat As SharpDX.DirectWrite.TextFormat, Width As Single, Align As ContentAlignment) As System.Drawing.SizeF
Dim layout As SharpDX.DirectWrite.TextLayout =
New SharpDX.DirectWrite.TextLayout(New DirectWrite.Factory, Message, textFormat, Width, textFormat.FontSize)
Return New System.Drawing.SizeF(layout.Metrics.Width, layout.Metrics.Height)
End Function
https://stackoverflow.com/questions/12671893
复制相似问题