Search code examples
androidandroid-canvas

How to draw a text inside a box on canvas with DynamicLayout and Ellipsize


I need to draw a text on canvas inside a specific box. I'm already using DynamicLayout to automatically calculate and break lines to fit inside the box width. Now I need to ellipsize the text automatically to fit the box height.

How can I achieve this? It doesn't necessarily need to be by the height (pixels), it could be by the max number of lines.


Example:

"This is a sample text to fit inside the box"

Actual Result:

------------
|This is a |
|text to   |
|fit inside|
------------
 the box   

Expected Result:

------------
|This is a |
|text to   |
|fit in... |
------------

I create the DynamicLayout like this:

textLayout = new DynamicLayout(mText, mTextPaint, 100, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);

And then I draw it like this:

canvas.save();
canvas.translate(500, 500 - textLayout.getHeight() / 2);
textLayout.draw(canvas);
canvas.restore();

Solution

  • As I know the number of lines (mMaxLines) that fit inside the box, I extended the DynamicLayout and I overrided a few methods:

    @Override
    public int getLineCount() {
        if (super.getLineCount() - 1 > mMaxLines) {
            return mMaxLines;
        }
        return super.getLineCount() - 1;
    }
    
    @Override
    public int getEllipsisCount(int line) {
        if (line == mMaxLines - 1 && super.getLineCount() - 2 > line) {
            return 1;
        }
        return 0;
    }
    
    @Override
    public int getEllipsisStart(int line) {
        if (line == mMaxLines - 1 && super.getLineCount() - 2 > line) {
            return getLineEnd(line) - getLineStart(line) - 1;
        }
        return 0;
    }
    

    Then I have the following result:

    ------------
    |This is a |
    |text to   |
    |fit in... |
    ------------