drawText()文本居中显示

        int circleXY = (int) (mWidth / 2);
        int circleRadius = (int) ((mWidth * 0.5) / 2) + 20;
        //计算文本宽度
        int textWidth = getTextWidth(mTextPaint,mText);
        //计算baseline:垂直方向居中
        Paint.FontMetricsInt fontMetrics = mTextPaint.getFontMetricsInt();
        int baseline = (getMeasuredHeight() - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
        Rect bounds = new Rect();
        mTextPaint.getTextBounds(mText, 0, mText.length(), bounds);
        int textX = (circleXY-textWidth)/2+circleRadius-20;
        canvas.drawText(mText,textX,baseline,mTextPaint);    
/**
     * 获取文本的宽度
     * @param paint
     * @param str
     * @return
     */
    public static int getTextWidth(Paint paint, String str) {
        int iRet = 0;
        if (str != null && str.length() > 0) {
            int len = str.length();
            float[] widths = new float[len];
            paint.getTextWidths(str, widths);
            for (int j = 0; j < len; j++) {
                iRet += (int) Math.ceil(widths[j]);
            }
        }
        return iRet;
    }
原文地址:https://www.cnblogs.com/hacjy/p/7017832.html