Use this function to draw correctly with word wrap
, new line break
and text alignment
features -
static void drawTextWithStaticLayout(Canvas canvas, float x, float y, String text, int wrapWidth, TextPaint paint,Layout.Alignment alignment) {
if (android.os.Build.VERSION.SDK_INT <= 15) {
StaticLayout sl = new StaticLayout(text,paint, wrapWidth, alignment,1.0f,0.0f,false);
sl.draw(canvas);
}
else {
float originalTextSize = paint.getTextSize();
final float magnifier = 1000f;
canvas.save();
canvas.translate(x,y);
canvas.scale(1f / magnifier, 1f / magnifier);
paint.setTextSize(originalTextSize * magnifier);
StaticLayout sl = new StaticLayout(text,paint, (int)magnifier*wrapWidth, alignment,1.0f,0.0f,false);
sl.draw(canvas);
canvas.restore();
paint.setTextSize(originalTextSize);
}
}