Android文本的测量和绘制

翻译与Chris Banes的博客   原文地址


如果你想手动在Android Canvas上画些什么东西,你最好从绘制文本开始。


文本绘制之前,你需要知道测量文本的绘制位置,计算文本X/Y轴的位置。

                                                                                       

最近我在一款APP中,需要在横向和纵向的画布上绘制一些以文本为中心的文字。于是我用了下面这些代码:


Paint mTextPaint = new Paint();  
mTextPaint.setTextAlign(Paint.Align.CENTER); // Center the text

// Later when you draw...
canvas.drawText(mText, // Text to display  
        mBounds.centerX(), // Center X of canvas bounds
        mBounds.centerY(), // Center Y of canvas bounds
        mTextPaint
);

我没想到代码的运行后竟然是下面的这个样子:





测量文本


接下来,我尝试定位文本,计算了文本的高宽度,并且修改了绘制文本X轴Y轴的位置:


int mTextWidth, mTextHeight; // Our calculated text bounds  
Paint mTextPaint = new Paint();

// Now lets calculate the size of the text
Rect textBounds = new Rect();  
mTextPaint.getTextBounds(mText, 0, mText.length(), textBounds);  
mTextWidth = textBounds.width();  
mTextHeight = textBounds.height();

// Later when you draw...
canvas.drawText(mText, // Text to display  
        mBounds.centerX() - (mTextWidth / 2f),
        mBounds.centerY() + (mTextHeight / 2f),
        mTextPaint
);

这一次我们做的已经相当接近了,但是你可以看到文本还是没有居中。




为了确定我没看到的原因,我用Paint.getTextBounds()计算一个矩形,并画在了文本的后面。




正如你看到的,文本的高宽绘制在了计算范围之外。


另一中测量文本的方法


在这个基础点上,我看到Paint另一种计算文本宽度的方法:Paint.measureText()


这个方法只能计算宽度而不能计算高度,因此我尝试结合两种方法:


int mTextWidth, mTextHeight; // Our calculated text bounds  
Paint mTextPaint = new Paint();

// Now lets calculate the size of the text
Rect textBounds = new Rect();  
mTextPaint.getTextBounds(mText, 0, mText.length(), textBounds);  
mTextWidth = mTextPaint.measureText(mText); // Use measureText to calculate width  
mTextHeight = textBounds.height(); // Use height from getTextBounds()

// Later when you draw...
canvas.drawText(mText, // Text to display  
        mBounds.centerX() - (mTextWidth / 2f),
        mBounds.centerY() + (mTextHeight / 2f),
        mTextPaint
);

这几下就做出了完美居中的文本。悠嘻!





  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值