自定义View画文字时居中于一个点

============================
自定义View用Canvas画文字时,需要让整个字符串在某个点居中显示,比如字符串的中心点必须位于坐标(50,50)处。

下面是一个简单的自定义TextView,以此来说明如何让字符串居中显示。代码中的注释笔记详细了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* Created by Rockon.
* 自定义TextView,字符串能根据一个点居中显示。
* 比如,居中点坐标为(300, 300),则整个字符串的中心点处于这个居中点上。
* 为了显示明显,在居中点画一个蓝色的圆点,字符串则对这个圆点居中显示。
*/

public class CustomTextview extends View {

/**
* 画文字的paint
*/
private Paint mTextPaint;

/**
* 画文字中心点的paint
*/
private Paint mPointPaint;

/**
* 字符串
*/
private String mText = "Hello, I'm Rockon here. Nice to meet you.";

/**
* 字符串居中点的横坐标
*/
private int mCenterX;

/**
* 字符串居中点的纵坐标
*/
private int mCenterY;

/**
* 字符串居中点的圆点的半径
*/
private int mCenterRadius;

/**
* 字符串文字大小
*/
private int mTextSize;

public CustomTextview(Context context) {
this(context, null);
}

public CustomTextview(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public CustomTextview(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 在(mCenterX,mCenterY)坐标出画一个蓝色的圆点,用于标记字符串的中点
canvas.drawCircle(mCenterX, mCenterY, mCenterRadius, mPointPaint);
Rect bounds = new Rect();
// 获取字符串的大小, bounds.width就是字符串的宽度
mTextPaint.getTextBounds(mText, 0, mText.length(), bounds);
// 字符串在X轴的中点
int strCenterX = bounds.width() / 2;
// 字符串在X轴的起点
int strStartX = mCenterX - strCenterX;
// 字符串在Y轴的中点,因为字符串的高不仅仅只包含字符串,还会包含字符串周围的空白,所以不是除以2。
int strCenterY = bounds.height() / 4;
// 字符串在Y轴的起点,起点是字符串左上角的点的Y坐标,要让字符串处于居中点上,则需要下移Y坐标。
int strStartY = mCenterY + strCenterY;
// 画字符串,在(mCenterX,mCenterY)坐标出居中显示
canvas.drawText(mText, strStartX, strStartY, mTextPaint);
}

/**
* 初始化变量
* <br/>
*/
private void init() {
// 初始化居中点坐标、居中点半径和文字大小
mCenterX = 300;
mCenterY = 300;
mCenterRadius = 10;
mTextSize = 30;

// 初始化字符串画笔
mTextPaint = new Paint();
mTextPaint.setColor(Color.RED);
mTextPaint.setTextSize(mTextSize);
mTextPaint.setAntiAlias(true);

// 初始化居中点画笔
mPointPaint = new Paint();
mPointPaint.setAntiAlias(true);
mPointPaint.setColor(Color.BLUE);
}
}

效果图:


原创,转载请指明出处(http://blog.xinspace.xin)。