1.寬度測量是比較簡單的,直接使用 float textWidht=mPaint.measureText("加入購物車");
返回float類型的值即為字符串寬度值
2.高度測量
Paste_Image.png
top跟ascent之間會有一定的間隙,當(dāng)精確度要求不高時可以使用
Rect rect = new Rect();
String s="加入購物車";
mPaint.getTextBounds(s,0,s.length(),rect);//將字符串的長寬信息保存在rect里
int widht=rect.width();//字符串寬度
int height=rect.height();//字符串高度
1.基準(zhǔn)點是baseline
2.ascent:是baseline之上至字符最高處的距離秉宿,為負(fù)值
3.descent:是baseline之下至字符最低處的距離陨献,為正值
精確測量
方法一
float textHeight=mPaint.descent()-mPaint.ascent();
方法二
Paint.FontMetrics fm = mPaint.getFontMetrics();
float textHight=fm.descent-fm.ascent;
使用:
canvas.drawText(String text, float x, float y,Paint paint)方法用來畫字符串,其中x為起始點的橫坐標(biāo)纽匙,注意y為baseline的縱坐標(biāo)厌丑,而不是起始點的縱坐標(biāo)
//mWidth是view的寬度,mHight是view的高度
mPaint.setTextSize(text_size);
float textWidth = mPaint.measureText("加入購物車");
canvas.drawText("加入購物車", (mWidht - textWidth) / 2,
(mHeight - (mPaint.descent() - mPaint.ascent())) / 2 - mPaint.ascent(), mPaint);