11

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

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

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

4

2 回答 2

16

See code below to calculate the required size (look for "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);
}
于 2015-06-19T11:38:10.463 回答
3

如果您使用 的 来创建 a ,CanvasTextLayout就像在 的示例中一样,您可能希望在 Win2D 1.23 中禁用自动换行。喜欢:requestedWidth0Michael Vach

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

(我不允许评论)

于 2018-09-20T15:48:55.683 回答