How to draw large sized text on a canvas?

不问归期 提交于 2019-11-28 11:33:11

The problem is that you're drawing text at one size and scaling the result up. Once you've determined how wide you want the text to be, you should use calls to Paint.measureText(), adjusting the size via Paint.setTextSize() accordingly. Once it measures correctly, then you do your call to Canvas.drawText().

An alternative would be to not measure the text at all and just immediately call:

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

There's no guarantee the text will fit in this case, though.

None of your other transform calls should result in interpolation, so it should give you very sharp lines.

Edit

Here is a code sample and comparison screenshot:

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);

I don't have enough reputation to comment on Krylez's excellent answer, but I'd like to reply to mcfly soft's comment/question about paths.

The idea is the same for paths as text. Instead of scaling and translating the canvas a path is drawn on, put the same scaling and translation into a matrix and pass that to 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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!