android精確繪製文字位置的方法

來源:互聯網
上載者:User

標籤:android   c   class   blog   code   java   

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相對於基準而言的。這個資訊足夠我們找准文字的中心了。


最後上一下代碼:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.