2010-10-25 92 views
7

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

这可能吗?我知道我可以测量字符串,砍掉一个字符,再次测量等等,直到尺寸合适......并且我确信还有更有效的方法......但是我想避免重新创建如果我可以的话。

回答

16

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

+0

冷静,那这样做是由于 – rob 2010-10-25 18:42:00

+1

将是很好,如果你能提前显示你如何完成这个抢一些代码...谢谢。 :) – Wesley 2012-07-06 14:24:25

+2

这可以用于多行文本吗?它似乎只支持基于宽度的单行文本。 – 2012-09-28 22:39:17

10

下面是一个例子:

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); 
+1

,你节省了我的时间! – 2015-12-18 12:02:13