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);
				
			
				
			}
			
			
		}
		
	}

原文地址:https://www.cnblogs.com/brucemengbm/p/6734946.html