【问题标题】:MeasureString in sharpDXSharpDX 中的测量字符串
【发布时间】:2018-12-01 21:08:13
【问题描述】:

我们正在使用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));

我们试图在不使用Windows.Graphics 的情况下找出MeasureString。可能吗?或者有没有其他方法可以在SharpDX 中获取MeasureString 或使用Direct2D

【问题讨论】:

  • 你需要看看 DirectWrite,有一些 SharpDX 示例。

标签: direct2d sharpdx


【解决方案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);
}

【讨论】:

    【解决方案2】:

    我修改了第一个答案以解决在 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
    

    【讨论】:

      猜你喜欢
      • 2017-05-07
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      • 2011-01-22
      相关资源
      最近更新 更多