android Canvas drawText 文字居中

1首先利用canvas获取画布的宽高,

//获取屏幕的宽和高
int width = canvas.getWidth();
int height = canvas.getHeight();

2获取文字的宽度,

    private int getTextWidth(Paint paint, String text){

        int iRet = 0;

        if (text != null && text.length() > 0) {

            int len = text.length();

            float[] widths = new float[len];

            paint.getTextWidths(text, widths);

            for (int j = 0; j < len; j++) {

                iRet += (int) Math.ceil(widths[j]);

            }

        }

        return iRet;

    }

3计算文字最左边的位置。

 分析了一下,假如我们知道画布宽度为200,文字宽度为100;那么我们有如下公式计算文字最左边的位置;

100+2x=200

  那么我们求解x就是我们text在绘制的时候left的值。

  eg:

String text = getResources().getString(R.string.scan_text);

int textLeft = (width-getTextWidth(paint,text))/2;

canvas.drawText(text,textLeft, (float) (frame.bottom + (float)TEXT_PADDING_TOP *density), paint);

你可能感兴趣的:(android)