问题描述
我正在使用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,CellHeight,Colors.Red,1.0f);
drawingSession.DrawTextLayout(textLayout,xLoc,Colors.Blue);
drawingSession.DrawRectangle(xLoc,yLoc + 100,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()
获取指定区域的文本宽度,并将其与预设宽度进行比较,以获取呈现的文本溢出的位置。
但是在渲染文本时,某些字符可能无法完全渲染,因此在获取溢出文本时,我又增加了一个字符。