繁体   English   中英

如何使用 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);
    }

Output:

在此处输入图像描述

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

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

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()获取指定区域的文字宽度,与预设宽度进行比较,得到渲染文字溢出的position。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM