Android文本的測量和繪製

來源:互聯網
上載者:User

標籤:canvas   android   textview   app   部落格   

翻譯與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 textRect 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 textRect 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);

這幾下就做出了完美置中的文本。悠嘻!





相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.