首先,我們看下這個方法參數的含義:canvas.drawText(text, x, y, paint),第一個參數是我們需要繪制的文本,第四個參數是我們的畫筆,這兩個不用多說,主要是第二和第三個參數的含義,這兩個參數在不同的情況下的值還是不一樣的
x默認是這個字符串的左邊在屏幕的位置,如果設置了paint.setTextAlign(Paint.Align.CENTER);那就是字符的中心.
y是指定這個字符baseline在屏幕上的位置,大家記住了,不要混淆,y不是這個字符中心在屏幕上的位置,而是baseline在屏幕上的位置。
那么什么是baseline呢?
Paste_Image.png
下面我們來看一下例子
先看一下onDraw的代碼如下
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
String testString = "測試:gafaeh:1234";
Paint mPaint = new Paint();
mPaint.setStrokeWidth(3);
mPaint.setTextSize(40);
mPaint.setColor(Color.RED);
mPaint.setTextAlign(Align.LEFT);
Rect bounds = new Rect();
mPaint.getTextBounds(testString, 0, testString.length(), bounds);
canvas.drawText(testString, getMeasuredWidth()/2 - bounds.width()/2, getMeasuredHeight()/2 + bounds.height()/2, mPaint);
}
效果如下,很明顯這個效果不對
Paste_Image.png
這個文本不是垂直居中,往下偏了一點,我前面說了y不是這個字符中心在屏幕上的位置,而是baseline在屏幕上的位置,而我們的代碼canvas.drawText(testString, getMeasuredWidth()/2 - bounds.width()/2, getMeasuredHeight()/2 + bounds.height()/2,mPaint);是y在垂直的中央,這是不對的,現在代碼修改如下:
protected void onDraw(Canvas canvas) {
String testString = "測試:gafaeh:1234";
Paint mPaint = new Paint();
mPaint.setStrokeWidth(3);
mPaint.setTextSize(40);
mPaint.setColor(Color.RED);
mPaint.setTextAlign(Align.LEFT);
Rect bounds = new Rect();
mPaint.getTextBounds(testString, 0, testString.length(), bounds);
FontMetricsInt fontMetrics = mPaint.getFontMetricsInt();
int baseline = (getMeasuredHeight() - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
canvas.drawText(testString,getMeasuredWidth() / 2 - bounds.width() / 2, baseline, mPaint);
}
Paste_Image.png
本文博客地址:
http://blog.csdn.net/e_Inch_Photo/article/details/60981766