Paint.getTextBounds() returns to big height

百般思念 提交于 2019-12-11 03:37:41

问题


EDIT: The problem came from the emulator, the error did not appear on a real device :(

I'm trying to draw some text in a custom view and must there for measure it but the value of the Paint.getTextBounds() returns a height which is about 30% higher then the actual text which gives everything a quirky look.

I found this: Android Paint: .measureText() vs .getTextBounds() and tried to add the solution code to my own onDraw and saw that i the same measuring error as in my code. Here is a picture of the result:

Compare with:

The image is copied from Android Paint: .measureText() vs .getTextBounds()

Note the spacing above the text in the first picture. Any Ideas what might be causing this? Or are there alternative ways to measure height of a drawn string?

Here is the onDraw method:

@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:


i didnot test your code but i dont see any problems with 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);
    }
}

add this in Activity.onCreate:

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

the result is:



来源:https://stackoverflow.com/questions/19425306/paint-gettextbounds-returns-to-big-height

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!