我正在使用 Win2D 开发一个 UWP 应用程序,我想将某些文本放置在定义宽度和高度的 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()
获取指定区域的文本宽度,并与预设宽度进行比较,从而得到渲染文本溢出的位置。
但是在渲染文本时,有些字符可能渲染不完全,所以在获取溢出文本时,我又取了一个字符。