android drawText在组件的中心

private void drawText(Canvas canvas) {

    if (!CommentUtil.isEmpty(mText)) {
        //获取文字宽度
        Rect bounds = new Rect();
        mPaint.setColor(Color.parseColor("#FFF45F1F"));
        mPaint.setTextSize(ScreenUtil.dpToPx(16,getResources()));
        mPaint.getTextBounds(mText, 0, mText.length(), bounds);
        int mTextwidth=bounds.width()/2;//文字一半的宽度
        int mTexthight=bounds.height()/2;//文字一半的高度度
        Paint.FontMetricsInt fontMetrics1 = mPaint.getFontMetricsInt();
        int baseline1 = (getMeasuredHeight() - fontMetrics1.bottom + fontMetrics1.top) / 2 - fontMetrics1.top;

        //getMeasuredWidth() / 2-mTextwidth 获取文字开始写的位置,baseline1代表屏幕中间
        //这里是计算了开始的位置,并且向上移了6dp
        canvas.drawText(mText, getMeasuredWidth() / 2-mTextwidth, baseline1-mTexthight-ScreenUtil.dpToPx(6,getResources()), mPaint);

        mPaint.setColor(Color.parseColor("#FF172F4D"));
        mPaint.setTextSize(ScreenUtil.dpToPx(14,getResources()));
        mPaint.getTextBounds("新风险", 0, "新风险".length(), bounds);
        Paint.FontMetricsInt fontMetrics2 = mPaint.getFontMetricsInt();
        //getMeasuredWidth() / 2-mTextwidth 获取文字开始写的位置,baseline1代表屏幕中间
        //这里是计算了开始的位置,并且向下移了6dp
        int baseline2 = (getMeasuredHeight() - fontMetrics2.bottom + fontMetrics2.top) / 2 - fontMetrics2.top;
        int mNewwidth=bounds.width()/2;//文字一半的宽度
        int mNewhight=bounds.height()/2;//文字一半的高度度

        canvas.drawText("新风险", getMeasuredWidth() / 2-mNewwidth, baseline2+mNewhight+ScreenUtil.dpToPx(6,getResources()), mPaint);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28674511/article/details/80856182
今日推荐