怎样在canvas中的方形中央画Text

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
/**
*
* @param canvas The canvas you need to draw on.
* @param x The X Coordinate from left to right.
* @param y The Y Coordinate form bottom to top.
*/
private void drawPopup(Canvas canvas,String num,int x,int y){
int bottomTriangleHeight = 12;
int padding = MyUtils.dip2px(mContext,2);
int marginBottom = MyUtils.dip2px(mContext,5);
boolean singularNum = (num.length() == 1);
int sidePadding = MyUtils.dip2px(mContext,singularNum? 8:5);
int xCoor = xCoordinateList.get(x);
int yCoor = yCoordinateList.get(yCoordinateList.size()-y)-MyUtils.dip2px(mContext,5);

Paint textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setColor(Color.BLACK);
textPaint.setTextSize(MyUtils.sp2px(mContext, 13));
textPaint.setStrokeWidth(5);
textPaint.setTextAlign(Paint.Align.CENTER);
Paint.FontMetrics fm = new Paint.FontMetrics();
textPaint.getFontMetrics(fm);

Rect r = new Rect((int)(xCoor-textPaint.measureText(num)/2)-sidePadding,
(int)(yCoor - textPaint.getTextSize())-bottomTriangleHeight-padding-marginBottom,
(int)(xCoor + textPaint.measureText(num)/2)+sidePadding,
yCoor+padding-marginBottom);

NinePatchDrawable popup = (NinePatchDrawable)getResources().
getDrawable(R.drawable.popup_red);
popup.setBounds(r);
popup.draw(canvas);

textPaint.setColor(Color.WHITE);
canvas.drawText(num, xCoor, yCoor-bottomTriangleHeight-marginBottom, textPaint);
}

被这个折腾死了。。