绘制时钟——Java
绘制的效果图如下所示:
绘制步骤
- 绘制外圆
- 绘制数字
- 绘制刻度点
- 绘制时针
- 绘制分针
- 绘制秒针
备注: 最外红框是控件的大小
绘制圆的知识点
- 弧度和角度关系
绘制外圆
先获取控件的宽度和高度,宽高各一半作为圆心。即
x = 宽度 / 2
y = 高度 / 2
r :半径
绘制数字
private void drawText(Canvas canvas) {
// 获取文字高度用于设置文本垂直居中
float textsize = paintNum.getFontMetrics().bottom - paintNum.getFontMetrics().top;
String[] number = {"3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "1", "2"};
// 数字离圆心的距离,26为刻度的长度,20文字大小
int distance = r_w - 26 - 20;
// 数字的坐标(a,b)
float a, b;
for (int i = 0; i < 12; i++) {
double rad = 2 * Math.PI / 12 * i;
a = x_w + (float) (Math.cos(rad) * distance);
b = y_w + (float) (Math.sin(rad) * distance);
canvas.drawText(number[i], a, b + textsize / 3, paintNum);
}
}
绘制刻度
private void drawPoits(Canvas canvas) {
int distance = r_w - 18;
float a, b;
for (int i = 0; i < 60; i++) {
double rad = 2 * Math.PI / 60 * i;
a = x_w + (float) (Math.cos(rad) * distance);
b = y_w + (float) (Math.sin(rad) * distance);
//修改点点颜色
if (i % 5 == 0) {
paintPoint.setColor(Color.BLACK);
canvas.drawCircle(a, b, 2, paintPoint);
} else {
paintPoint.setColor(Color.GRAY);
canvas.drawCircle(a, b, 2, paintPoint);
}
}
}
绘制时针
private void drawHours(Canvas canvas, int hour, int minute) {
/***
* 旋转是度数
*/
float degrees = 30 * hour + minute / 2;
canvas.rotate(degrees, x_w, y_w);
paintHour.setStrokeCap(Paint.Cap.ROUND);
canvas.drawLine(x_w, y_w, x_w, y_w - 80, paintHour);
//这里画好了时钟,我们需要再将画布转回来,继续以12整点为0°参照点
canvas.rotate(-degrees, x_w, y_w);
}
绘制分针
private void drawMinute(Canvas canvas, int minute, int second) {
/***
* 旋转是度数
*/
float degrees = 6 * minute + second / 10;
canvas.rotate(degrees, x_w, y_w);
paintMinute.setStrokeCap(Paint.Cap.ROUND);
canvas.drawLine(x_w, y_w, x_w, y_w - 98, paintMinute);
canvas.rotate(-degrees, x_w, y_w);
}
绘制秒针
private void drawSeconds(Canvas canvas, int second) {
/***
* 旋转是度数
*/
float degrees = 6 * second;
canvas.rotate(degrees, x_w, y_w);
canvas.drawLine(x_w, y_w, x_w, y_w - 120, paintSecond);
canvas.rotate(-degrees, x_w, y_w);
}