【问题标题】:How to calculate the size of a piece of text in Win2DWin2D中如何计算一段文字的大小
【发布时间】:2015-08-22 04:38:02
【问题描述】:

我正在使用 Win2D 为 Windows 10 编写一个应用程序,并且我正在尝试绘制一个可以动态缩放以适应其中的任何文本的形状。

我想做的是用给定的 CanvasTextFormat 计算一个特定的字符串有多大,然后用它来设置形状的大小。

我的问题是我似乎找不到计算字符串大小的方法?

【问题讨论】:

    标签: c# windows win2d


    【解决方案1】:

    查看下面的代码来计算所需的大小(查找“theRectYouAreLookingFor”)

    private void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
    {
        CanvasDrawingSession drawingSession = args.DrawingSession;
        float xLoc = 100.0f;
        float yLoc = 100.0f;
        CanvasTextFormat format = new CanvasTextFormat {FontSize = 30.0f, WordWrapping = CanvasWordWrapping.NoWrap};        
        CanvasTextLayout textLayout = new CanvasTextLayout(drawingSession, "Hello World!", format, 0.0f, 0.0f);
        Rect theRectYouAreLookingFor = new Rect(xLoc + textLayout.DrawBounds.X, yLoc + textLayout.DrawBounds.Y, textLayout.DrawBounds.Width, textLayout.DrawBounds.Height);
        drawingSession.DrawRectangle(theRectYouAreLookingFor, Colors.Green, 1.0f);
        drawingSession.DrawTextLayout(textLayout, xLoc, yLoc, Colors.Yellow);
    }
    

    【讨论】:

    • 我确实发现 CanvasTextLayout 的 LayoutBounds 属性对我来说比 DrawBounds 更有用。也许其他人也会。
    • 没有drawingSession就可以得到尺寸吗?我想根据文本的高度调整画布的大小。
    【解决方案2】:

    如果您使用0requestedWidth 创建CanvasTextLayout,例如Michael Vach,您可能希望在Win2D 1.23 中禁用自动换行。喜欢:

    var textLayout = new CanvasTextLayout(drawingSession, "Hello World!", fontFormat, 0.0f, 0.0f) {
                WordWrapping = CanvasWordWrapping.NoWrap
    };
    var completeOuterSize = textLayout.LayoutBounds
    

    (我不能评论)

    【讨论】:

    • 你不需要道歉。无论如何,对现有答案的实质性改进都值得单独回答。此外,您将无法在注释中很好地格式化代码。因此,主要的代码示例应该始终包含在答案中。顺便提一句。如果你想引用another answer(或question),你可以点击share链接并在你的文本中使用它。
    猜你喜欢
    • 2021-01-06
    • 2014-06-23
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 2011-03-30
    相关资源
    最近更新 更多