android钟表,Android画个时钟玩玩

这篇博客详细介绍了如何在Android中通过自定义View来实现一个钟表的效果,包括设置测量模式、重写onMeasure和onDraw方法,以及绘制表盘、刻度、指针等元素。通过设置最小尺寸、利用canvas旋转方法简化计算,并用线程更新时间来实现动态指针转动。
摘要由CSDN通过智能技术生成

先看下最终的效果

ebb726f8fc0b

开始实现

新建一个ClockView集成View

public class ClockView extends View {

}

先重写onMeasure方法,这里要先说一下View的测量模式,一共有三种:

EXACTLY

即精确值模式,当我们将控件的layout_width属性或layout_height属性指定为具体数值时,比如android:layout_width="100dp",或者指定为math_parent属性时(占据父View的大小),系统使用的是EXACTLY模式。

AT_MOST

即最大值模式,当控件的layout_width属性或layout_height属性指定为wrap_content时,控件大小一般随着控件的子控件或内容的变化而变化,此时控件的尺寸只要不超过父控件允许的最大尺寸即可。

UNSPECIFIED

这个属性比较奇怪——它不指定其大小测量模式,View想多大就多大,通常情况下在绘制自定义View时才会使用。

因为View的onMeasure方法只支持EXACTLY模式,当layout_width和layout_height为wrap_content时,View的大小就显得很奇怪了,如下图。

ebb726f8fc0b

所以我们重写一下onMeasure方法可以指定View width、height的最小值

/**

* 当布局为wrap_content时设置默认长宽

* @param widthMeasureSpec

* @param heightMeasureSpec

*/

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

setMeasuredDimension(measure(widthMeasureSpec), measure(heightMeasureSpec));

}

private int measure(int origin){

int result = DEFAULT_MIN_WIDTH;

int specMode = MeasureSpec.getMode(origin);

int specSize = MeasureSpec.getSize(origin);

if(specMode == MeasureSpec.EXACTLY){

result = specSize;

}else{

if(specMode == MeasureSpec.AT_MOST){

result = Math.min(result, specSize);

}

}

return result;

}

下面就是最重要的重写onDraw方法来绘制表盘、刻度、指针……,大致流程如下

画表盘,用drawCircle绘制一个圆作为表盘, 圆心坐标为(getWidth()/2, getHeight()/2),半径为Math.min(getHeight()/2, getWidth()/2)。

//画外圆

float borderWidth = DEFAULT_BORDER_WIDTH;

Paint paintCircle = new Paint();

paintCircle.setStyle(Paint.Style.STROKE);

paintCircle.setAntiAlias(true);

paintCircle.setStrokeWidth(borderWidth);

canvas.drawCircle(getWidth() / 2, getHeight() / 2, Math.min(getHeight() / 2, getWidth() / 2) - borderWidth / 2, paintCircle);

画刻度线,在这里我们可以利用一个`canvas.rotate'方法就可以不用计算角度了

//画刻度线

float degreeLength = 0f;

Paint paintDegree = new Paint();

paintDegree.setAntiAlias(true);

for(int i=0;i<60;i++){

if(i % 5 == 0){

paintDegree.setStrokeWidth(6);

degreeLength = DEFAULT_LONG_DEGREE_LENGTH;

}else{

paintDegree.setStrokeWidth(3);

degreeLength = DEFAULT_SHORT_DEGREE_LENGTH;

}

canvas.drawLine(getWidth()/2, Math.abs(getWidth()/2 - getHeight()/2), getWidth()/2, Math.abs(getWidth()/2 - getHeight()/2) + degreeLength, paintDegree);

canvas.rotate(360/60, getWidth()/2, getHeight()/2);

}

画刻度上的数字

//刻度数字

int degressNumberSize = 30;

canvas.translate(getWidth() / 2, getHeight() / 2);

Paint paintDegreeNumber = new Paint();

paintDegreeNumber.setTextAlign(Paint.Align.CENTER);

paintDegreeNumber.setTextSize(degressNumberSize);

paintDegreeNumber.setFakeBoldText(true);

for(int i=0;i<12;i++){

float[] temp = calculatePoint((i+1)*30, r - DEFAULT_LONG_DEGREE_LENGTH - degressNumberSize/2 - 15);

canvas.drawText((i+1)+"", temp[2], temp[3] + degressNumberSize/2-6, paintDegreeNumber);

}

/**

* 根据角度和长度计算线段的起点和终点的坐标

* @param angle

* @param length

* @return

*/

private float[] calculatePoint(float angle, float length){

float[] points = new float[4];

if(angle <= 90f){

points[0] = -(float) Math.sin(angle*Math.PI/180) * DEFAULT_POINT_BACK_LENGTH;

points[1] = (float) Math.cos(angle*Math.PI/180) * DEFAULT_POINT_BACK_LENGTH;

points[2] = (float) Math.sin(angle*Math.PI/180) * length;

points[3] = -(float) Math.cos(angle*Math.PI/180) * length;

}else if(angle <= 180f){

points[0] = -(float) Math.cos((angle-90)*Math.PI/180) * DEFAULT_POINT_BACK_LENGTH;

points[1] = -(float) Math.sin((angle-90)*Math.PI/180) * DEFAULT_POINT_BACK_LENGTH;

points[2] = (float) Math.cos((angle-90)*Math.PI/180) * length;

points[3] = (float) Math.sin((angle-90)*Math.PI/180) * length;

}else if(angle <= 270f){

points[0] = (float) Math.sin((angle-180)*Math.PI/180) * DEFAULT_POINT_BACK_LENGTH;

points[1] = -(float) Math.cos((angle-180)*Math.PI/180) * DEFAULT_POINT_BACK_LENGTH;

points[2] = -(float) Math.sin((angle-180)*Math.PI/180) * length;

points[3] = (float) Math.cos((angle-180)*Math.PI/180) * length;

}else if(angle <= 360f){

points[0] = (float) Math.cos((angle-270)*Math.PI/180) * DEFAULT_POINT_BACK_LENGTH;

points[1] = (float) Math.sin((angle-270)*Math.PI/180) * DEFAULT_POINT_BACK_LENGTH;

points[2] = -(float) Math.cos((angle-270)*Math.PI/180) * length;

points[3] = -(float) Math.sin((angle-270)*Math.PI/180) * length;

}

return points;

}

画指针

//画指针

Paint paintHour = new Paint();

paintHour.setAntiAlias(true);

paintHour.setStrokeWidth(15);

Paint paintMinute = new Paint();

paintMinute.setAntiAlias(true);

paintMinute.setStrokeWidth(10);

Paint paintSecond = new Paint();

paintSecond.setAntiAlias(true);

paintSecond.setStrokeWidth(5);

Calendar now = Calendar.getInstance();

float[] hourPoints = calculatePoint(now.get(Calendar.HOUR_OF_DAY)%12/12f*360, hourPointerLength);

canvas.drawLine(hourPoints[0], hourPoints[1], hourPoints[2], hourPoints[3], paintHour);

float[] minutePoints = calculatePoint(now.get(Calendar.MINUTE)/60f*360, minutePointerLength);

canvas.drawLine(minutePoints[0], minutePoints[1], minutePoints[2], minutePoints[3], paintMinute);

float[] secondPoints = calculatePoint(now.get(Calendar.SECOND)/60f*360, secondPointerLength);

canvas.drawLine(secondPoints[0], secondPoints[1], secondPoints[2], secondPoints[3], paintSecond);

画圆心

//画圆心

Paint paintCenter = new Paint();

paintCenter.setColor(Color.WHITE);

canvas.drawCircle(0, 0, 2, paintCenter);

最后只要启动一个无限循环的线程,每隔1秒针重绘一下View就能让指针动起来了

private Thread timeThread = new Thread() {

@Override

public void run() {

try {

while(true){

updateHandler.sendEmptyMessage(0);

Thread.sleep(1000);

}

} catch (InterruptedException e) {

e.printStackTrace();

}

}

};

private Handler updateHandler = new Handler() {

@Override

public void handleMessage(Message msg) {

invalidate();

}

};

全部测试代码下载地址:

欢迎留言交流,如有描述不当或错误的地方还请留言告知

以下是一个简单的Android Canvas绘制钟表的示例代码: ```java public class MyClockView extends View { private Paint mCirclePaint; private Paint mLinePaint; private Paint mTextPaint; private Paint mHourHandPaint; private Paint mMinuteHandPaint; private Paint mSecondHandPaint; private float mHour; private float mMinute; private float mSecond; public MyClockView(Context context) { super(context); init(); } public MyClockView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public MyClockView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { mCirclePaint = new Paint(); mCirclePaint.setAntiAlias(true); mCirclePaint.setStyle(Paint.Style.STROKE); mCirclePaint.setStrokeWidth(5); mCirclePaint.setColor(Color.BLACK); mLinePaint = new Paint(); mLinePaint.setAntiAlias(true); mLinePaint.setStyle(Paint.Style.STROKE); mLinePaint.setStrokeWidth(3); mLinePaint.setColor(Color.BLACK); mTextPaint = new Paint(); mTextPaint.setAntiAlias(true); mTextPaint.setStyle(Paint.Style.FILL); mTextPaint.setTextSize(30); mTextPaint.setColor(Color.BLACK); mHourHandPaint = new Paint(); mHourHandPaint.setAntiAlias(true); mHourHandPaint.setStyle(Paint.Style.STROKE); mHourHandPaint.setStrokeWidth(8); mHourHandPaint.setColor(Color.BLACK); mMinuteHandPaint = new Paint(); mMinuteHandPaint.setAntiAlias(true); mMinuteHandPaint.setStyle(Paint.Style.STROKE); mMinuteHandPaint.setStrokeWidth(5); mMinuteHandPaint.setColor(Color.BLACK); mSecondHandPaint = new Paint(); mSecondHandPaint.setAntiAlias(true); mSecondHandPaint.setStyle(Paint.Style.STROKE); mSecondHandPaint.setStrokeWidth(3); mSecondHandPaint.setColor(Color.RED); // 获取当前时间 Calendar calendar = Calendar.getInstance(); mHour = calendar.get(Calendar.HOUR_OF_DAY); mMinute = calendar.get(Calendar.MINUTE); mSecond = calendar.get(Calendar.SECOND); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 获取控件宽高 int width = getWidth(); int height = getHeight(); // 计算圆的半径 int radius = Math.min(width, height) / 2 - 10; // 画圆 canvas.drawCircle(width / 2, height / 2, radius, mCirclePaint); // 画刻度线和数字 for (int i = 0; i < 12; i++) { canvas.save(); canvas.translate(width / 2, height / 2); canvas.rotate(i * 30); canvas.drawLine(0, -radius, 0, -radius + 30, mLinePaint); canvas.drawText(String.valueOf(i + 1), -10, -radius + 60, mTextPaint); canvas.restore(); } // 画时针 canvas.save(); canvas.translate(width / 2, height / 2); canvas.rotate(mHour * 30 + mMinute / 2); canvas.drawLine(0, 0, 0, -radius / 2, mHourHandPaint); canvas.restore(); // 画分针 canvas.save(); canvas.translate(width / 2, height / 2); canvas.rotate(mMinute * 6); canvas.drawLine(0, 0, 0, -radius * 3 / 4, mMinuteHandPaint); canvas.restore(); // 画秒针 canvas.save(); canvas.translate(width / 2, height / 2); canvas.rotate(mSecond * 6); canvas.drawLine(0, 0, 0, -radius + 20, mSecondHandPaint); canvas.restore(); // 刷新时间 postInvalidateDelayed(1000); } } ``` 在xml布局文件中添加MyClockView: ```xml <com.example.myapp.MyClockView android:layout_width="match_parent" android:layout_height="match_parent"/> ``` 运行效果如下图所示: ![image](https://user-images.githubusercontent.com/543384/136059427-20c4b3c3-e3c8-4e2d-b0d1-7e5bfc8b9d11.png)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值