android精确绘制文字位置的方法

android 中使用Canvas的drawText绘制文本的位置,是基于基线的。

例如以下图:

当中字母Q的小尾巴在横线以下了。


怎么样找准字母的中心位置呢?

先看以下的样例:(右边的数字,表示字体的 left, top, right, bottom)


这里面的关键是Paint.getTextBound。 getTextBound会填充一个Rect,这个Rect表示的就是一个字的left, top, right, bottom。

注意到left和top并非从0,0開始的。 left和right应该是从0坐标開始的。而top和bottom相对于基线而言的。这个信息足够我们找准文字的中心了。


最后上一下代码:

		@Override
		public void onDraw(Canvas canvas) {
			
			mPaint.setTextSize(40f);
			mPaint.setAntiAlias(true);
			
			mPaint.setColor(0xffff0000);
			canvas.drawText(alphas, 30, 60, mPaint);
			mPaint.setColor(0xff000000);
			canvas.drawLine(0, 60, 1000, 60, mPaint);
			
			
			for(int i = 0; i < alphas.length(); i ++)  {
				int y = i*70+100;
				
				mPaint.getTextBounds(alphas, i, i+1, mBound);
				
				mPaint.setColor(0xff000000);
				canvas.drawText(String.format("%d,%d,%d,%d", mBound.left,mBound.top, mBound.right,mBound.bottom), 150, y, mPaint);
				
				mPaint.setColor(0xffff0000);
				canvas.drawCircle(60, y, 30, mPaint);

				mPaint.setColor(0xffffffff);
				canvas.drawText(alphas, i, i+1, 60 - (mBound.right + mBound.left)/2, y - (mBound.bottom + mBound.top)/2, mPaint);
				mPaint.setColor(0xff000000);
				canvas.drawLine(30, y, 90, y, mPaint);
				canvas.drawLine(60, y-30, 60, y+30, mPaint);
				
			
				
			}
			
			
		}
		
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值