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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM