Will Will - 3 months ago 9
Android Question

Wrapping long text on an Android Canvas

I have a custom control that is doing a lot of 2D drawing straight to the

canvas
.

Some of this drawing is text, so I am using the
Canvas.drawText()
method.

I want to draw the text within some bounds - a top-left, certain maximum width, and a maximum number of lines. After drawing the text, I want to know how many lines it took.

Is there a built-in function to draw text within bounds doing the splitting sensibly?

If not, is there a standard recipe for doing so?

Answer

You can use the android.text.StaticLayout class for this; simply create a StaticLayout for the desired text, alignment, width, etc. and call its draw(Canvas) method to draw to the canvas.