首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >sharpDX中的MeasureString

sharpDX中的MeasureString
EN

Stack Overflow用户
提问于 2012-10-01 18:52:37
回答 2查看 1.8K关注 0票数 4

我们正在使用SharpDX开发Windows8 metro应用程序。现在我们必须在Rectangle中声明一组字符串集。为此,我们尝试使用SharpDX.DrawingSizeF找出字体的宽度和高度。例如:

代码语言:javascript
运行
复制
Windows.Graphics g;
Model.Font font;
DrawingSizeF size = g.MeasureString(quote, font.Font, new DrawingSizeF(font.Width, font.Height));

我们正在尝试找出不使用Windows.GraphicsMeasureString。有可能吗?或者,有没有其他方法可以在SharpDX中或使用Direct2D获取MeasureString

EN

回答 2

Stack Overflow用户

发布于 2017-03-07 23:26:53

我从this messageboard post得到了一些适合我的代码。在我自己摆弄了一下之后,我最终得到了以下结果:

代码语言:javascript
运行
复制
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);
}

如果您插入文本、字体、建议的宽度和对齐方式,它将导出一个矩形的大小以容纳文本。当然,您需要的是高度,但这包括宽度,因为文本很少填满整个空间。

注意:按照评论者的建议,实际上应该是以下代码来处置资源:

代码语言:javascript
运行
复制
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
EN

Stack Overflow用户

发布于 2018-12-01 21:08:14

我修改了第一个答案,以解决在VB.net中无法访问DXFont的限制:

代码语言:javascript
运行
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12671893

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档