Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

draw text "ellipsized" to a canvas

Tags:

android

I need to draw text to a canvas (of a custom view), and need to first trim it to a maximum width, adding an ellipsis at the end if necessary. I see you can do it for a TextView, but I want to do it inside a custom view's onDraw() without having to add a child view.

Is this possible? I know I could measure the string, chop off a character, measure again, etc until it is the right size....and I'm sure there are more efficient ways as well...but I'd like to avoid reinventing that wheel if I can.

like image 861
rob Avatar asked Oct 25 '10 06:10

rob


2 Answers

Take a look at TextUtils.ellipsize(). I think it's exactly what you want. Basically you just tell it the amount of space available and using the other state information it will create the correct text for you. :)

like image 89
Greg Giacovelli Avatar answered Nov 13 '22 03:11

Greg Giacovelli


Here is an example:

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);
like image 22
Asterius Avatar answered Nov 13 '22 01:11

Asterius