Using android.text.StaticLayout

In a recent project, I had to implement a small status text overlay on top of a avatar image.

The requirement were to have it display 4 lines at most and use the space most efficiently.

My first thought was to start calculating margins, text widths and padding etc. Luckily, Android provides a class called android.text.StaticLayout.

Unfortunately, it doesn’t provide a setMaxLines(int) function that could be used, therefore the line limitation was solved by using clipRect on the canvas.

// bmp1 is a source bitmap (in that case 44x44px big).
// density is the screen density, you will need to retrieve it yourself as well.
 
canvas.drawBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.overlay_44x44), new Matrix(), null);
 
// Initialize using a simple Paint object.
final TextPaint tp = new TextPaint(WHITE);
 
// Save the canvas state, it might be re-used later.
canvas.save();
 
// Create a padding to the left & top.
canvas.translate(4*density, 4*density);
 
// Clip the bitmap now.
canvas.clipRect(new Rect(0, 0, bmp1.getWidth(),(int) (bmp1.getHeight() - (6*density))));
 
// Basic StaticLayout with mostly default values
StaticLayout sl = new StaticLayout(message, tp, bmp1.getWidth(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
sl.draw(canvas);
 
// Restore canvas.
canvas.restore();

Published by

Sebastian

Android Developer.

4 thoughts on “Using android.text.StaticLayout”

  1. I am doing something similar to this, but I would want the last line to not wrap off the bottom but instead be trimmed. Is that possible?

Leave a Reply

Your email address will not be published. Required fields are marked *