自定义View --画个钟表
github 源码地址
https://github.com/comerss/TimeKeeper
- 效果图
-
我们需要知道钟表的坐标圆心,这里我设定屏幕的中心点为圆心,那我们首先要测量控件自己的宽高。
mWidth = getMeasuredWidth();
mHeight = getMeasuredHeight(); -
那么我们的圆心也就能计算出来了 宽高的一半
float radio = (float) (Math.min(mWidth, mHeight) * 0.8);//直径
-
绘制表盘
//表盘 刻度其实一直是在0°处画的横线,通过旋转画布得到所有的刻度,Y不变 X根据自己想要的刻度的长短自己设置一个值
private void drawCircle(Canvas canvas, float radio) {
mPaint.setColor(Color.GRAY);
canvas.drawCircle(mWidth / 2, mHeight / 2, radio / 2, mPaint);
canvas.drawPoint(mWidth / 2, mHeight / 2, mPaint);
canvas.save();//保存旋转前的canvas状态
for (int i = 0; i < 60; i++) {
if (i % 5 == 0) {//每5个画一个大格,其他的画小格
mPaint.setColor(Color.RED);
mPaint.setStrokeWidth(4);
canvas.drawLine(mWidth / 2 + radio * 9 / 20, mHeight / 2, mWidth / 2 + radio / 2, mHeight / 2, mPaint);
} else {
mPaint.setColor(Color.GRAY);
mPaint.setStrokeWidth(1);
canvas.drawLine(mWidth / 2 + radio * 9 / 20, mHeight / 2, mWidth / 2 + radio / 2, mHeight / 2, mPaint);
}
canvas.rotate(6, mWidth / 2, mHeight / 2);
}
canvas.restore();//恢复到旋前的状态
} -
绘制表针
private void drawNeedle(Canvas canvas, float radio) {
mCalendar.setTimeInMillis(System.currentTimeMillis());
int Hour = mCalendar.get(Calendar.HOUR) % 12;
int Minute = mCalendar.get(Calendar.MINUTE);
int Second = mCalendar.get(Calendar.SECOND);//时针 int degree = 360 / 12 * Hour; //弧度 double w = Math.toRadians(degree); int startX = mWidth / 2; int startY = mHeight / 2; int endX = (int) (mWidth / 2 + radio * Math.cos(w) * 0.2); int endY = (int) (mHeight / 2 + radio * Math.sin(w) * 0.2); canvas.save(); mPaint.setColor(Color.RED); mPaint.setStrokeWidth(4); canvas.rotate(-90, mWidth / 2, mHeight / 2); canvas.drawLine(startX, startY, endX, endY, mPaint); //分针 canvas.restore(); degree = 360 / 60 * Minute; w=Math.toRadians(degree); endX = (int) (mWidth / 2 + radio * Math.cos(w) * 0.3); endY = (int) (mHeight / 2 + radio * Math.sin(w) * 0.3); canvas.save(); mPaint.setColor(Color.GRAY); mPaint.setStrokeWidth(3); canvas.rotate(-90, mWidth / 2, mHeight / 2); canvas.drawLine(startX, startY, endX, endY, mPaint); canvas.restore(); //秒针 degree = 360 / 60 *Second; w=Math.toRadians(degree); endX = (int) (mWidth / 2 + radio * Math.cos(w) * 0.4); endY = (int) (mHeight / 2 + radio * Math.sin(w) * 0.4); canvas.save(); mPaint.setColor(Color.GREEN); mPaint.setStrokeWidth(2); canvas.rotate(-90, mWidth / 2, mHeight / 2); canvas.drawLine(startX, startY, endX, endY, mPaint); canvas.restore(); }
下一篇: 实验吧-简单的登录题