画一个圆,圆心为(cx,cy),并以此为中心,写数字:
通常情况下,drawText(text,cx,xy,paint)中,点(cx,cy)是文字的起始点,如下:
即使使用paint.setTextAlign(Paint.Align.CENTER),是文字横向居中,但是纵向不会居中。如果能得到文字高度,再向下位移一半,就可以居中了:
先要取得text的边界,paint.getTextBounds(,,,textBounds);
取得了边界,就可计算高度,宽度。
Paint countPaint = new Paint(Paint.ANTI_ALIAS_FLAG
| Paint.DEV_KERN_TEXT_FLAG);
countPaint.setColor(Color.BLUE);
countPaint.setTextSize(20f);
countPaint.setTypeface(Typeface.DEFAULT_BOLD);
countPaint.setTextAlign(Paint.Align.CENTER);
Rect textBounds = new Rect();
String numberStr = String.valueOf(number);
countPaint.getTextBounds(numberStr, 0, numberStr.length(), textBounds);//get text bounds, that can get the text width and height
int textHeight = textBounds.bottom - textBounds.top;
Log.i("TAG","bounds: left = "+textBounds.left + ", right = "+textBounds.right+", top = "+textBounds.top+", bottom = "+textBounds.bottom);
canvas.drawText(numberStr, cx, cy + textHeight/2,
countPaint);