如何使用 C# 在 Win2D 中的 CanvasTextLayout 中裁剪后获取剩余文本?

How to get the remaining text after clipping in CanvasTextLayout in Win2D using C#?

我正在使用 Win2D 开发一个 UWP 应用程序,我想在其中将某些文本放置在定义了宽度和高度的 Rect(矩形)中。如果文本超过 Rect 的宽度,那么我想根据 Rect 的宽度裁剪文本。在这里,我想显示适合 Rect 的文本以及被剪裁的文本。如何使用 C# 在 Win2D 的 CanvasTextLayout 中做到这一点?

    CanvasDrawingSession drawingSession;

    private void Draw(CanvasControl sender, CanvasDrawEventArgs args)
    {
        drawingSession = args.DrawingSession;
        float xLoc = 100.0f;
        float yLoc = 100.0f;
        float CellWidth = 100.0f;
        float CellHeight = 30.0f;

        String fontFamily = "Tahoma";
        int fontsize = 16;
        FontStyle fontStyle = FontStyle.Normal;
        FontWeight fontWeight = FontWeights.Normal;
        string text = "abcdefghijklmnopqrstuvwxyz";
        CanvasTextFormat format = GetTextFormat(fontFamily, fontsize, fontWeight, fontStyle);
        CanvasTextLayout textLayout = new CanvasTextLayout(drawingSession, text, format, CellWidth, CellHeight);            
        textLayout.WordWrapping = CanvasWordWrapping.NoWrap;
        textLayout.Options = CanvasDrawTextOptions.Clip;

        drawingSession.DrawRectangle(xLoc, yLoc,CellWidth,CellHeight, Colors.Red, 1.0f);
        drawingSession.DrawTextLayout(textLayout, xLoc, yLoc, Colors.Blue);

        drawingSession.DrawRectangle(xLoc, yLoc + 100, CellWidth, CellHeight, Colors.Blue, 1.0f);
    }

输出:

我在这里显示红色矩形内的文本(以剪切形式 - “abcdefghijklm”)。还想在蓝色矩形内显示剩余的剪辑文本(“nopqrstuvwxyz”)。怎么做?

Win2D并没有提供一定的API直接获取截断的文本,但是我有一个想法,就是通过计算文本的宽度来判断当前输入文本被截断的位置。

private void Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
    ...
    if (textLayout.LayoutBounds.Width > CellWidth)
    {
        int length = text.Length;
        int index = 0;
        for (; index < length; index++)
        {
            var regions = textLayout.GetCharacterRegions(0, index);
            if (regions.Length > 0)
            {
                var region = regions.First();
                if (region.LayoutBounds.Width > CellWidth)
                    break;
            }
        }
        string trimmed = text.Substring(index - 1);

        var textLayout2 = new CanvasTextLayout(drawingSession, trimmed, format, CellWidth, CellHeight);
        textLayout2.WordWrapping = CanvasWordWrapping.NoWrap;
        textLayout2.Options = CanvasDrawTextOptions.Clip;
        drawingSession.DrawTextLayout(textLayout2, xLoc, yLoc + 100, Colors.Red);
    }
}

我们可以通过textLayout.GetCharacterRegions()获取指定区域的文字宽度,与预设宽度进行比较,得到渲染文字溢出的位置

但是在渲染文字的时候,有些字符可能渲染不完全,所以在获取溢出文字的时候,我多取了一个字符。