如何在画布上绘制大尺寸文字?

Sas*_*h0k 5 android drawtext android-canvas

我想在画布月份的文字垂直沿着屏幕高度绘制.

绘制初始化:

   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);
Run Code Online (Sandbox Code Playgroud)

画画:

   // 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();
Run Code Online (Sandbox Code Playgroud)

结果在hdpi屏幕上看起来不错,但在xhdpi上非常难看和像素化.

我在各种设备上做了更多测试,并了解结果取决于Android版本,而不是屏幕密度和分辨率.

代码在2.x平台上运行良好,但在4.0.3+上不起作用.假设,这里改变了Android绘图实现.完整代码,你可以在这里看到.

hdpi版本 2.3.5(也测试 2.2)

华电国际

xhdpi版本 4.2(也测试了 4.1, 4.0.3)

xhdpi

为油漆抗锯齿尝试不同的变化,亚像素文本没有效果.我该如何解决这个问题?

Kry*_*lez 10

问题是您正在以一种尺寸绘制文本并将结果缩放.一旦确定了文本的宽度,就应该使用对Paint.measureText()的调用,相应地通过Paint.setTextSize()调整大小.一旦它正确测量,然后你调用Canvas.drawText().

另一种方法是根本不测量文本,只需立即调用:

paint.setTextSize(paint.getSize() * scale)
Run Code Online (Sandbox Code Playgroud)

但是,不能保证文本适合这种情况.

你的其他变换调用都不应该导致插值,所以它应该给你非常清晰的线条.

编辑

这是一个代码示例和比较截图:

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);
Run Code Online (Sandbox Code Playgroud)

你的渲染方法在顶部,我的底部