1.效果展示
2.手表控件
2.1表盘实现
画圆形表盘的条件
float centerX = getWidth() / 2.0f;//圆心X坐标
float centerY = getWidth() / 2.0f;//圆心Y坐标
float radius = getWidth() / 2.0f - 10;//半径(1/2宽稍微偏移一点,给圆盘留一些绘制宽度)
用canvas绘制圆形表盘
public void drawCircle(float cx, float cy, float radius, @NonNull Paint paint);
Draw the specified circle using the specified paint. If radius is <= 0, then nothing will be
drawn. The circle will be filled or framed based on the Style in the paint.@param cx The x-coordinate of the center of the circle to be drawn @param cy The y-coordinate of the center of the circle to be drawn @param radius The radius of the circle to be drawn @param paint The paint used to draw the circle
canvas.drawCircle(centerX, centerY, radius, paint);
2.2刻度盘实现
用path画线来实现,从(width/2, height开始画,大刻度和小刻度通过偏移量和角度来控制)
int offset = 50;//默认偏移(绘制小刻度的默认长度)
if (angle == 0 || angle == 90 || angle == 180 || angle == 270) {
offset = 100;//分别是12点,3点,6点,9点的大刻度长度
}
path.moveTo(centerX, getHeight() - 10); //从视图宽度的1/2,底部开始绘制
path.lineTo(centerX, getHeight() - 10 - offset) //要绘制的线条长度(区分大刻度和小刻度)
matrix.setRotate(angle, centerX, centerY);//用matrix来控制旋转,这样就可以用角度绘制整个圆盘的刻度
path.transform(matrix);
canvas.drawPath(path, paint);
//表盘主要时间点文字绘制。简单的drawText操作,绘制的位置脱离表盘实现,主要是与表盘解耦
//绘制时需要注意文字的长度很高度,否则绘制出来的时间点是偏向某一方向的
String timeText;
if (angle == 0) {
timeText = "12";
float text_width = paint.measureText(timeText);
canvas.drawText(timeText, centerX - text_width / 2.0f, getHeight() * 0.2f, paint);
} else if (angle == 90) {
timeText = "3";
Rect rect = new Rect();
paint.getTextBounds(timeText, 0, timeText.length(), rect);
int height = rect.height();
canvas.drawText(timeText, getWidth() * 0.8f, centerY + height / 2.0f, paint);
} else if (angle == 180) {
timeText = "6";
float text_width = paint.measureText(timeText);
canvas.drawText(timeText, centerX - text_width / 2.0f, getHeight() * 0.8f, paint);
} else if (angle == 270) {
timeText = "9";
Rect rect = new Rect();
paint.getTextBounds(timeText, 0, timeText.length(), rect);
int height = rect.height();
canvas.drawText(timeText, getHeight() * 0.2f, centerY +