direct2d - sharpDX 中的 MeasureString

标签 direct2d sharpdx

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

我们正在努力找出MeasureString不使用 Windows.Graphics .是否可以?或者还有其他方法可以获取MeasureStringSharpDX或使用 Direct2D ?

最佳答案

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

关于direct2d - sharpDX 中的 MeasureString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12671893/

相关文章:

windows-8.1 - 在通用应用程序共享项目中包含 .targets 文件以包含自定义构建操作

directx-11 - DirectX11 交换链和窗口失去全屏状态

c - 每次调整窗口大小时内存都会增加

c++ - 使用 Direct2d 绘制和创建非矩形位图

c++-cli - Windows 7 上的 D3D D2D 互操作

c# - 我的 SharpDX 应用程序中存在内存泄漏

c# - 在 Windows Phone 8 中同时播放两个音频文件的最佳方式

c# - XAudio2 - 播放生成的正弦波,当改变频率时点击声音

c++ - SetLineSpacing() 在 DirectWrite 中不起作用 - 为什么?

c++ - 使用 Direct2D 绘制 SVG 路径 : Can't draw elliptical arc