方法參數(shù)解讀
/**
* Draw the text, with origin at (x,y), using the specified paint. The
* origin is interpreted based on the Align setting in the paint.
*
* @param text The text to be drawn
* @param x The x-coordinate of the origin of the text being drawn
* @param y The y-coordinate of the origin of the text being drawn
* @param paint The paint used for the text (e.g. color, size, style)
*/
第二個(gè)參數(shù):baseLine 的 x值
第三個(gè)參數(shù):baseLine 的 y值
public void drawText(@NonNull String text, float x, float y, @NonNull Paint paint) {} 參數(shù)解讀
方法一
首先自己動(dòng)手做實(shí)驗(yàn)呀忧,自己定一個(gè)baseline泻蚊,然后把文字畫上去,再畫上FontMetrics的幾條線钞速。FontMetrics里是字體圖樣的信息贷掖,有float型和int型的版本,都可以從Paint中獲取渴语。它的每個(gè)成員數(shù)值都是以baseline為基準(zhǔn)計(jì)算的苹威,所以負(fù)值表示在baseline之上。
Rect targetRect = new Rect(0, 0, getMeasuredWidth(), getMeasuredHeight()); //文字在 targetRect 居中
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStrokeWidth(3);
paint.setTextSize(80);
String testString = "測(cè)試:ijkJQKA:1234";
paint.setColor(Color.BLACK);
canvas.drawRect(targetRect, paint);
paint.setColor(Color.RED);
Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
// 轉(zhuǎn)載請(qǐng)注明出處:http://blog.csdn.net/hursing
//int baseline = targetRect.centerY() - (fontMetrics.bottom + fontMetrics.top) / 2;一樣
int baseline = (targetRect.bottom + targetRect.top - fontMetrics.bottom - fontMetrics.top) / 2;
paint.setTextAlign(Paint.Align.CENTER); //注意,drawText 對(duì)應(yīng)改為傳入targetRect.centerX()
canvas.drawText(testString, targetRect.centerX(), baseline, paint);
核心代碼:
*寫法1
paint.setTextAlign(Paint.Align.CENTER); //注意,drawText對(duì)應(yīng)改為傳入targetRect.centerX()
canvas.drawText(testString, targetRect.centerX(), baseline, paint);
*寫法2
Rect mTextRect = new Rect();
paint.getTextBounds(testString, 0, testString.length(), mTextRect);
int x = targetRect.centerX() - mTextRect.centerX();
canvas.drawText(testString, x, baseline, paint);
方法二
- init 中通過制定的 Paint 對(duì)象計(jì)算 mTextBound
mBackPaint.setStyle(Style.FILL);
mBackPaint.setTextScaleX(2f);
mBackPaint.setColor(Color.BLACK); // 繪畫字體的顏色
mBackPaint.setTextSize(30);
mBackPaint.getTextBounds(mText, 0, mText.length(), mTextBound);
- 在 onDraw 中
//控制好+-號(hào)驾凶, 計(jì)算width時(shí): 計(jì)算height時(shí):
canvas.drawText(mText, (getWidth() - mTextBound.width()) / 2
,(getHeight() + mTextBound.height()) / 2, mBackPaint);