2

编辑:问题来自模拟器,错误没有出现在真实设备上:(

我正在尝试在自定义视图中绘制一些文本,并且必须在那里进行测量,但 Paint.getTextBounds() 的值返回的高度比实际文本高约 30%,这使所有内容看起来都很古怪。

我发现了这个:Android Paint: .measureText() vs .getTextBounds()并尝试将解决方案代码添加到我自己的 onDraw 中,发现我的测量错误与我的代码中的相同。这是结果的图片: 在此处输入图像描述

比较: 在此处输入图像描述 图像是从 Android Paint 复制的:.measureText() vs .getTextBounds()

注意第一张图片中文字上方的间距。任何想法可能导致这种情况?还是有其他方法来测量绘制字符串的高度?

这是 onDraw 方法:

@Override 
public void onDraw(Canvas canvas){
//      canvas.drawColor(color_Z1);
//      r.set(0, 0, (int)(width*progress), height);
//      paint.setColor(color_Z2);
////        canvas.drawRect(r, paint);
//      textPaint.getTextBounds(text, 0, text.length(), r);
//      canvas.drawRect(r, paint);
//      canvas.drawText(text, 0, r.height(), textPaint);

    final String s = "Hello. I'm some text!";

     Paint p = new Paint();
     Rect bounds = new Rect();
     p.setTextSize(60);

     p.getTextBounds(s, 0, s.length(), bounds);
     float mt = p.measureText(s);
     int bw = bounds.width();

     Log.i("LCG", String.format(
          "measureText %f, getTextBounds %d (%s)",
          mt,
          bw, bounds.toShortString())
      );
     bounds.offset(0, -bounds.top);
     p.setStyle(Style.STROKE);
     canvas.drawColor(0xff000080);
     p.setColor(0xffff0000);
     canvas.drawRect(bounds, p);
     p.setColor(0xff00ff00);
     canvas.drawText(s, 0, bounds.bottom, p);
}
4

1 回答 1

0

我没有测试你的代码,但我没有看到 Paint.getTextBounds() 有任何问题:

public class TextBoundsTest extends View {
    private Paint paint;
    private Rect bounds;

    public TextBoundsTest(Context context) {
        super(context);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setTextSize(32);
        bounds = new Rect();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        String text = "this is my text";
        paint.getTextBounds(text, 0, text.length(), bounds);
        Log.d(TAG, "onDraw " + bounds);

        int x = (getWidth() - bounds.width()) / 2;
        int y = 70;

        paint.setColor(0xff008800);
        bounds.offset(x, y);
        canvas.drawRect(bounds, paint);

        paint.setColor(0xffeeeeee);
        canvas.drawText(text, x, y, paint);
    }
}

在 Activity.onCreate 中添加:

TextBoundsTest view = new TextBoundsTest(this);
setContentView(view);

结果是: 在此处输入图像描述

于 2013-10-17T12:06:13.697 回答