How to draw a large size text on canvas?

I want to draw a vertical canvas in the format of the month in height of the screen.

Init paint:

   this.paint = new Paint();
   this.paint.setAntiAlias(true);
   this.paint.setDither(true);
   this.paint.setSubpixelText(true);
   this.paint.setColor(color_text_dark);
   this.paint.setTextAlign(Align.RIGHT);

Drawing:

   // Set the scale to the widest month
   float scale = getHeight() / this.max_month_width;
   String month_string = FULL_MONTH_NAME_FORMATTER.
                         format(active_month_calendar.getTime());
   canvas.save();
   canvas.translate(getWidth(), 0);
   canvas.rotate(-90);
   canvas.scale(scale, scale);
   canvas.drawText(month_string, 0, 0, this.paint);
   canvas.restore();

The result looks good on an hdpi screen, but is very ugly and pixelated on xhdpi.

I did more tests on different devices and realized what the result depends on the version of Android, and not on the screen density and resolution.

The code works fine on the 2.x platform, but does not work with 4.0.3+. Suppose in this case, the implementation of Android draw has been changed. You can see the full code here .

hdpi version 2.3.5 (also tested 2.2 )

hdpi

xhdpi version 4.2 (also tested 4.1 , 4.0.3 )

xhdpi

, . ?

+5
2

, . , , , , Paint.measureText(), Paint.setTextSize(). , Canvas.drawText().

:

paint.setTextSize(paint.getSize() * scale)

, .

, .

:

canvas.save();
canvas.scale(10, 10);
canvas.drawText("Hello", 0, 10, mTextPaint);
canvas.restore();
float textSize = mTextPaint.getTextSize();
mTextPaint.setTextSize(textSize * 10);
canvas.drawText("Hello", 0, 300, mTextPaint);
mTextPaint.setTextSize(textSize);

Your rendering method on top, mine on bottom

+9

, Krylez, mcfly soft comment/question about paths.

, . , Path.transform:

// instead of this:
canvas.scale(sX, sY);
canvas.translate(trX, trY);
canvas.drawPath(path);

// do this:
matrix.postScale(sX, sY);
matrix.postTranslate(trX, trY);
path.transform(matrix);
canvas.drawPath(path);
+1

All Articles