前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >绘制一个时钟

绘制一个时钟

作者头像
奶油话梅糖
发布2025-03-03 14:36:50
发布2025-03-03 14:36:50
2500
代码可运行
举报
运行总次数:0
代码可运行
开源

Gitee:https://gitee.com/rabbitTang_admin/TimeClockView

赞助

爱发电:http://afdian.net/@naiyouhuameitang

代码(ClockView.class)
代码语言:javascript
代码运行次数:0
复制
public class MyView extends View {
	Paint paint = new Paint();// 画笔
	int height = 0;// 高
	int width = 0;// 宽
	int radius = 0;// 圆心
	Canvas canvas;// 画布

	public MyView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onDraw(Canvas c) {
		// TODO Auto-generated method stub
		canvas = c;// 赋值,无所谓的操作,方便查看而已
		super.onDraw(canvas);
		width = canvas.getWidth() / 2;// 获取半径宽
		height = canvas.getHeight() / 2;// 获取半径高
		radius = height - 3;// 获取半径
		paint.setColor(Color.BLACK);// 设置画笔颜色
		paint.setStyle(Style.STROKE);// 设置画笔风格
		paint.setStrokeWidth(3);// 设置画笔粗细
		paint.setAntiAlias(true);// 设置抗锯齿
		// 绘制外圆
		canvas.drawCircle(width, height, radius, paint);
		// 循环绘制小刻度(分钟\秒)
		for (int i = 0; i < 60; i++) {
			canvas.save();
			canvas.rotate(i * 6, width, height);
			canvas.drawLine(width, height - radius, width,
					height - radius + 10, paint);
			canvas.restore();
		}
		// 循环绘制大刻度(小时)
		for (int i = 0; i < 12; i++) {
			canvas.save();
			canvas.rotate(i * 30, width, height);
			canvas.drawLine(width, height - radius, width,
					height - radius + 20, paint);
			canvas.restore();
		}
		// 循环绘制时间文本(1-12)
		for (int i = 1; i < 13; i++) {
			paint.setStrokeWidth(1);
			canvas.save();
			canvas.rotate(i * 30, width, height);
			canvas.drawText(String.valueOf(i), width - 5, height - radius + 40,
					paint);
			canvas.restore();
		}
		// 获取系统时间
		Calendar calendar = Calendar.getInstance();
		int hour = calendar.get(Calendar.HOUR);// 小时
		int min = calendar.get(Calendar.MINUTE);// 分钟
		int sec = calendar.get(Calendar.SECOND);// 秒
		// 设置画笔粗细
		paint.setStrokeWidth(15);
		// 设置画笔风格
		paint.setStyle(Style.FILL);
		/**
		 * 绘制指针 ↓
		 */
		// 绘制时针
		canvas.save();// 保存画布
		canvas.rotate(hour * 30 + min / 60 * 30, width, height);
		canvas.drawLine(width, height, width, height - 40, paint);
		// 绘制分针
		paint.setStrokeWidth(10);// 设置画笔粗细
		canvas.rotate(min * 6, width, height);
		canvas.drawLine(width, height, width, height - 50, paint);
		// 绘制秒针
		paint.setStrokeWidth(5);// 设置画笔粗细
		canvas.rotate(sec * 6, width, height);
		canvas.drawLine(width, height, width, height - 60, paint);
		canvas.restore();// 重置画布
		/**
		 * 绘制指针 ↑
		 */
		// 绘制小圆心
		canvas.drawCircle(width, height, 15, paint);
		// 重载View
		invalidate();
	}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-03-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 开源
  • 赞助
  • 代码(ClockView.class)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档