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.
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. :)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With