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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值