4

我们正在使用SharpDX. 现在我们必须在 a 中声明一组字符串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

4

2 回答 2

1

我从这个留言板帖子中得到了一些对我很有效的代码。在我自己的一些摆弄之后,我最终得到的是以下内容:

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);
}
于 2017-03-07T15:26:53.127 回答
1

我修改了第一个答案以解决在 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
于 2018-12-01T13:08:13.933 回答