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?
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.
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).
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.
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