如何计算Win2D中一段文本的大小

Dom*_*yre 8 c# windows win2d

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

我想要做的是弄清楚给定CanvasTextFormat的特定字符串有多大,然后使用它来设置形状的大小.

我的问题是我似乎无法找到一种方法来计算字符串的大小?

小智 12

请参阅下面的代码来计算所需的大小(查找"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);
}
Run Code Online (Sandbox Code Playgroud)

  • 我确实发现CanvasTextLayout的LayoutBounds属性对我来说比DrawBounds更有用.也许其他人也会这样. (2认同)