17

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.

rob
  • 9,933
  • 7
  • 42
  • 73

2 Answers2

26

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. :)

Mark Whitaker
  • 8,465
  • 8
  • 44
  • 68
Greg Giacovelli
  • 10,164
  • 2
  • 47
  • 64
  • 1
    would be nice if you could show some code on how you accomplished this rob... thanks in advance. :) – Wesley Jul 06 '12 at 14:24
  • 2
    Can this be used for multi-line text? It appears to only support single line text based on the width alone. – James Wald Sep 28 '12 at 22:39
  • @JamesWald You can split the text into two parts, main and remainder. The main won't get truncated, and use `TextUtils.ellipsize().` to truncate the remainder. – York May 18 '16 at 03:55
23

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);
Asterius
  • 2,180
  • 2
  • 19
  • 27