sharpDX中的MeasureString

时间:2012-10-01 10:52:37

标签: direct2d sharpdx

我们正在使用SharpDX开发Windows 8 metro app。现在我们必须在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。可能吗?或者是否有其他方法可以MeasureStringSharpDX使用Direct2D

2 个答案:

答案 0 :(得分:1)

我从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);
}

答案 1 :(得分:0)

我修改了第一个答案,以解决无法访问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