2

I'm currently using the following method to draw some text to the SurfaceView:

canvas.drawText("someText", 0, 0, paint);

Yet what if the text exceeds the width of the screen? Is it possible to define a region wherein the text can be drawn?

So now when the string's width exceeds the rectangles width, the text will be formatted to fit underneath the above text and so on eg.

"sometext"
"text carried"
"on"
Simon Sarris
  • 62,212
  • 13
  • 141
  • 171
Luke Taylor
  • 9,481
  • 13
  • 41
  • 73

1 Answers1

1

Based on this answer, I believe this is what the Layout subclasses are used for. Per documentation:

A base class that manages text layout in visual elements on the screen.

For text that will be edited, use a DynamicLayout, which will be updated as the text changes. For text that will not change, use a StaticLayout.

And with each subclass there's a note:

This is used by widgets to control text layout. You should not need to use this class directly unless you are implementing your own widget or custom display object, or would be tempted to call Canvas.drawText() directly.

Which sounds exactly like what you're doing.

It's basically a replacement for canvas.drawText(). It can be used in this fashion:

TextPaint tPaint = new TextPaint(paint);
StaticLayout sLayout = new StaticLayout(sText, tPaint, mWidth, widthToFill, Layout.Alignment.ALIGN_CENTER, 1.2f, 1.0f, false);

canvas.save();
canvas.translate(posX, posY);
sLayout.draw(canvas);
canvas.restore();
Community
  • 1
  • 1
DeeV
  • 35,865
  • 9
  • 108
  • 95