将文本"ellipsized"绘制到画布上

rob*_*rob 13 android

我需要将文本绘制到画布(自定义视图),并且需要先将其修剪为最大宽度,必要时在末尾添加省略号.我看到你可以为TextView做这件事,但我想在自定义视图的onDraw()中进行,而不必添加子视图.

这可能吗?我知道我可以测量字符串,砍掉一个字符,再次测量等等,直到它的大小合适......而且我确信还有更有效的方法......但我想避免重新发明如果可以的那个轮子.

Gre*_*lli 21

看看TextUtils.ellipsize().我认为这正是你想要的.基本上你只是告诉它可用的空间量,并使用其他状态信息,它将为您创建正确的文本.:)

  • 这可以用于多行文本吗?它似乎只支持基于宽度的单行文本. (2认同)

Ast*_*ius 16

这是一个例子:

TextPaint textPaint = new TextPaint();//The Paint that will draw the text 
textPaint.setColor(Color.WHITE);//Change the color if your background is white!
textPaint.setStyle(Paint.Style.FILL);
textPaint.setAntiAlias(true);
textPaint.setTextSize(20);
textPaint.setTextAlign(Paint.Align.LEFT);
textPaint.setLinearText(true);

Rect b = getBounds(); //The dimensions of your canvas
int x0 = 5;           //add some space on the left. You may use 0
int y0 = 20;          //At least 20 to see your text
int width = b.getWidth() - 10; //10 to keep some space on the right for the "..."
CharSequence txt = TextUtils.ellipsize("The text", textPaint, width, TextUtils.TruncateAt.END);
canvas.drawText(txt, 0, txt.length(), x0, y0, textPaint);
Run Code Online (Sandbox Code Playgroud)