我一直在努力处理文本测量和缩放画布。
当画布未缩放时,getTextBounds 和measureText 可提供准确的结果。但是,当缩放画布时,这两种方法都无法提供与打印文本的实际大小相匹配的结果。
为了进行测试,我使用以下 onDraw 方法创建了 View 的子类:
final float scaling = 0.51f;
final int fontSize = 50;
canvas.scale(scaling, scaling);
font = Typeface.create("Arial", Typeface.NORMAL);
Paint paint = new Paint();
paint.setColor(0xff4444ff);
paint.setTypeface(font);
paint.setTextSize(fontSize);
paint.setAntiAlias(true);
int x = 10;
int y = 100;
final String text = "Lorem ipsum dolor sit amet, consectetur adipisici elit...";
canvas.drawText(text, x, y, paint);
// draw border using getTextBounds
paint.setColor(0xffff0000);
paint.setStyle(Paint.Style.STROKE);
paint.setTypeface(font);
paint.setTextSize(fontSize);
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
bounds.offset(x, y);
paint.setColor(0x80ffff00);
canvas.drawRect(bounds, paint);
// draw border using measureText
float w = paint.measureText(text);
bounds.left = x;
bounds.right = (int) Math.ceil(bounds.left + w);
bounds.top -= 10;
bounds.bottom += 10;
paint.setColor(0x8000ffff);
paint.setPathEffect(new DashPathEffect(new float[] { 10, 10 }, 0));
canvas.drawRect(bounds, paint);
for scaling = 0.5 I get the following output:
for scaling = 0.51 the following result is shown:
黄色实线边框标记从 getTextBounds 传递的矩形,青色虚线矩形使用从measureText 传递的宽度呈现。
如您所见,缩放 = 0.5 的文本小于测量的尺寸,缩放 = 0.51 时绘制的文本远大于测量的尺寸。
任何帮助表示赞赏!