Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

canvas drawtext with multiline

I am developing a image commenting application. I draw text in canvas with canvas.drawText(text, x, y, imgPaint);

This appears in a single line. I need to break the line to multiline when the text crosses the canvas width

Thanks in advance

like image 917
varghesekutty Avatar asked Feb 24 '15 07:02

varghesekutty


People also ask

How to draw multiline text on Canvas Android?

Positioning multiline text 📍draw(canvas) will draw the entire block of text (from its top left corner) at position (0, 0) on the Canvas . This is fine for simple use cases, but we may want to position the text elsewhere (as we are able to do with the default Canvas text drawing methods).

How do you make a bitmap on canvas?

Use the Canvas method public void drawBitmap (Bitmap bitmap, Rect src, RectF dst, Paint paint) . Set dst to the size of the rectangle you want the entire image to be scaled into. EDIT: Here's a possible implementation for drawing the bitmaps in squares across on the canvas.

What is TextPaint?

android.text.TextPaint. TextPaint is an extension of Paint that leaves room for some extra data used during text measuring and drawing.

What is static layout in Android?

StaticLayout is a Layout for text that will not be edited after it is laid out. Use DynamicLayout for text that may change. This is used by widgets to control text layout.


1 Answers

You need to use StaticLayout:

TextPaint mTextPaint=new TextPaint();
StaticLayout mTextLayout = new StaticLayout("my text\nNext line is very long text that does not definitely fit in a single line on an android device. This will show you how!", mTextPaint, canvas.getWidth(), Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);

canvas.save();
// calculate x and y position where your text will be placed

textX = 100;
textY = 100;

canvas.translate(textX, textY);
mTextLayout.draw(canvas);
canvas.restore();
like image 128
Kasra Avatar answered Sep 21 '22 08:09

Kasra