Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping long text on an Android Canvas

Tags:

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?

like image 782
Will Avatar asked Feb 25 '10 19:02

Will


People also ask

How do you wrap text in canvas HTML?

To wrap text in a canvas element with JavaScript, we have to do the calculation for wrapping the text ourselves. to create the canvas. Then we write: const wrapText = (ctx, text, x, y, maxWidth, lineHeight) => { const words = text.

How does canvas work on Android?

The Canvas class holds the "draw" calls. To draw something, you need 4 basic components: A Bitmap to hold the pixels, a Canvas to host the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect, Path, text, Bitmap), and a paint (to describe the colors and styles for the drawing).


1 Answers

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.

like image 91
Roman Nurik Avatar answered Oct 21 '22 04:10

Roman Nurik