相关疑难解决方法(0)

在缩放的画布上测量文本

我一直在努力学习文本测量和缩放画布.

当画布未缩放时,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 …
Run Code Online (Sandbox Code Playgroud)

fonts android canvas measure typeface

7
推荐指数
1
解决办法
4730
查看次数

标签 统计

android ×1

canvas ×1

fonts ×1

measure ×1

typeface ×1