前言

筆者最近在做一款彈幕控件,里面涉及到繪制文本,以及文本邊框。而繪制文本邊框需要知道文本的左邊位置,上邊位置,以及文本的寬高。
通常來說,使用 Canvas 繪制文本,可以通過畫筆 Paint 來設置文字的大小。但是畫筆的大小與文字的寬高并無直接關系。
大家應該能說上幾種測量文字寬高的方法,如:
方案1. 通過 Paint 的 measureText 方法,可以測量文字的寬度
方案2. 通過獲取 Paint 的 FontMetrics, 根據 FontMetrics 的 leading, ascent, 和 descent可以獲取文字的高度。
方案3. 通過 Paint 的 getTextBounds 獲取文本的邊界矩形 Rect,根據 Rect 可以計算出文字的寬高。
方案4. 通過 Paint 獲取文字的 Path, 根據 Path 獲取文本的邊界矩形 Rect, 根據 Rect 可以計算出文字的寬高。
表面上看,我們有以上四種方案可以獲取文字的寬或高。但是不幸的,這四種方案里,有些方法獲取到的數值不是真實的文字寬高。
我們通過以下測試代碼,分別測試字母 "e" 和 "j"。
private void measureText(String str) {
if (str == null) {
return;
}
float width2 = mPaint.measureText(str);
Log.i("lxc", "width2 ---> " + width2);
Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
float height1 = Math.abs(fontMetrics.leading + fontMetrics.ascent) + fontMetrics.descent;
Log.i("lxc", "height1 ---> " + height1);
Rect rect = new Rect();
mPaint.getTextBounds(str, 0, str.length(), rect);
float width3 = rect.width();
float height2 = rect.height();
Log.i("lxc", "width3 ---> " + width3);
Log.i("lxc", "height2 ---> " + height2);
Path textPath = new Path();
mPaint.getTextPath(str, 0, str.length(), 0.0f, 0.0f, textPath);
RectF boundsPath = new RectF();
textPath.computeBounds(boundsPath, true);
float width4 = boundsPath.width();
float height3 = boundsPath.height();
Log.i("lxc", "width4 ---> " + width4);
Log.i("lxc", "height3 ---> " + height3);
}
網頁名稱:Android精確測量文本寬高及基線位置的方法-創新互聯
標題鏈接:http://www.yijiale78.com/article20/cesijo.html
成都網站建設公司_創新互聯,為您提供用戶體驗、網站設計、移動網站建設、App設計、自適應網站、網站內鏈
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯