Paint.getTextBounds()返回大高度

时间:2013-10-17 11:20:20

标签: android ondraw

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

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

我发现了这个:Android Paint: .measureText() vs .getTextBounds()并尝试将解决方案代码添加到我自己的onDraw中,并且看到了与我的代码中相同的测量错误。这是结果的图片: enter image description here

比较: enter image description here 图像从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);
}

1 个答案:

答案 0 :(得分: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);

结果是: enter image description here