效果图:
Android简易钟表
代码:
Paint paint = new Paint();
public Clock_View(Context context) {
super(context);
}
public Clock_View(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float mx = getWidth() / 2;
float my = getHeight() / 2;
//绘制一个最外圈的圆
paint.setStrokeWidth(1);
canvas.drawCircle(mx, my, mx, paint);
//绘制中心圆
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(mx, my, 10, paint);
paint.setStyle(Paint.Style.STROKE);
/**
* 刻度绘制
*/
for (int i = 1; i <= 60; i++) {
canvas.save(); //画布保存
//旋转角度
canvas.rotate(i*6, mx, my);
if (i % 5 == 0) {
canvas.drawLine(mx, 0, mx, 20, paint);
canvas.drawText(i / 5+"", mx-5, 40, paint);
}else{
canvas.drawLine(mx, 0, mx, 10, paint);
}
canvas.restore(); //恢复画布
}
//获取时间
Calendar calendar = Calendar.getInstance();
//秒针
paint.setStrokeWidth(3);
canvas.save(); //画布保存
//360/60 = 6得出一秒的角度为6度
canvas.rotate(calendar.get(Calendar.SECOND)*6, mx, my);
canvas.drawLine(mx, my, mx, 40, paint);
canvas.restore(); //恢复画布
//分针
paint.setStrokeWidth(5);
canvas.save(); //画布保存
canvas.rotate(calendar.get(Calendar.MINUTE)*6, mx, my);
canvas.drawLine(mx, my, mx, 60, paint);
canvas.restore(); //恢复画布
//时针
paint.setStrokeWidth(7);
canvas.save(); //画布保存
/**
* 1h = 360/12 = 30度
* 1min = 1/60h
* 1min = 1*30/60度
*/
canvas.rotate(calendar.get(Calendar.HOUR)*30
+calendar.get(Calendar.MINUTE)*30/60, mx, my);
canvas.drawLine(mx, my, mx, 80, paint);
canvas.restore(); //恢复画布
//不断的绘制,展示钟表的效果(刷新)
invalidate();