Android Studio 使用 ImageView 或自定义 View 实现时钟模型
要在屏幕上显示一个时钟模型,您可以使用自定义 View 来实现。下面是一个简单的示例代码:\n\n首先,创建一个名为 ClockView 的自定义 View 类,并继承自 View 类:\n\njava\npublic class ClockView extends View {\n private Paint paint; \n private int width, height; \n\n public ClockView(Context context) {\n super(context);\n init();\n }\n\n public ClockView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init();\n }\n\n public ClockView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n init();\n }\n\n private void init() {\n paint = new Paint();\n paint.setColor(Color.BLACK);\n paint.setStyle(Paint.Style.STROKE);\n paint.setStrokeWidth(5);\n paint.setAntiAlias(true);\n\n Calendar calendar = Calendar.getInstance();\n width = calendar.get(Calendar.HOUR_OF_DAY) * 60 + calendar.get(Calendar.MINUTE);\n height = 100;\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n\n int centerX = getWidth() / 2; \n int centerY = getHeight() / 2; \n\n // 绘制表盘\n canvas.drawCircle(centerX, centerY, height / 2, paint);\n\n // 绘制时钟指针\n float angle = (float) (2 * Math.PI * width / (12 * 60));\n float handX = (float) (centerX + (height / 2 - 20) * Math.sin(angle));\n float handY = (float) (centerY - (height / 2 - 20) * Math.cos(angle));\n canvas.drawLine(centerX, centerY, handX, handY, paint);\n }\n}\n\n\n然后,在您的 Activity 布局文件中,使用 ClockView 作为一个自定义 View:\n\nxml\n<com.example.yourpackage.ClockView\n android:layout_width="wrap_content"\n android:layout_height="wrap_content"/>\n\n\n最后,在您的 Activity 中,找到 ClockView 并设置时间:\n\njava\nClockView clockView = findViewById(R.id.clockView);\nclockView.setTime(hour, minute); // 设置当前时间\n\n\n这样,您就可以在屏幕上显示一个时钟模型了。在 onDraw 方法中,我们使用 Canvas 绘制表盘和时钟指针。您可以根据自己的需求修改绘制的样式和位置。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/qFjM 著作权归作者所有。请勿转载和采集!