Android繪制鐘表的方法
本文實例為大家分享了Android繪制鐘表的具體代碼,供大家參考,具體內容如下
首先要畫一個表,我們要先知道步驟如何:
1、儀表盤----外面最大的圓盤
2、刻度線----四個長刻度和剩下的短刻度
3、刻度值----對應的刻度下的數字
4、指針------鐘表的三個指針
5、指針動起來
明確思路,下來就是畫圖了
1、儀表盤,畫圓
outCirclePaint = new Paint();outCirclePaint.setStrokeWidth(2);outCirclePaint.setAntiAlias(true);outCirclePaint.setStyle(Paint.Style.STROKE);canvas.drawCircle(mWidth/2,mHeight/2,mWidth/2,outCirclePaint);
2、畫刻度,同時寫刻度值
畫刻度的思路是每次畫一個刻度(短的線段)完成之后,旋轉畫布30°,因為360/12。遇到3、6、9、12 把刻度線畫粗,畫稍長一點。
for (int i = 0; i <= 12;i++){ if (i==3||i==6||i==9 || i==12){ degreePaint.setStrokeWidth(3); degreePaint.setTextSize(30); canvas.drawLine(mWidth/2,mHeight/2-mWidth/2,mWidth/2,mHeight/2-mWidth/2+30,degreePaint); String degree = String.valueOf(i); canvas.drawText(degree,mWidth/2-degreePaint.measureText(degree)/2,mHeight/2-mWidth/2 + 60,degreePaint); }else{ if (i!=0){ //遇到0不考慮劃線 寫刻度值 degreePaint.setStrokeWidth(2); degreePaint.setTextSize(20);canvas.drawLine(mWidth/2,mHeight/2-mWidth/2,mWidth/2,mHeight/2-mWidth/2+15,degreePaint);String degree = String.valueOf(i);canvas.drawText(degree, mWidth/2-degreePaint.measureText(degree)/2, mHeight/2-mWidth/2 + 40, degreePaint); } } canvas.rotate(30,mWidth/2,mHeight/2);}
3、畫指針
canvas.translate(mWidth/2,mHeight/2);canvas.drawLine(0,0,hx,hy,hourPaint); // 小時canvas.drawLine(0,0,mx,my,minPaint); // 分鐘canvas.drawLine(0,0,sx,sy,sPaint); // 秒
4、指針動起來
指針動起來也就是說讓指針的一端固定,另外一端需要通過sin計算Y值,cos計算X值,指針長度自己確定好即可。
這樣秒針每次動一下就是6°,以這個為秒針單位。
Math.PI/30 //π/30
分針同理
時針不一樣,每次動一下是要30°
Math.PI/6 //π/6
Calendar calendar = Calendar.getInstance();hcount = calendar.get(Calendar.HOUR_OF_DAY);mcount = calendar.get(Calendar.MINUTE);scount = calendar.get(Calendar.SECOND);int hx = (int) (70*Math.cos(Math.PI*(hcount%12-15) / 6)); int hy = (int) (70*Math.sin(Math.PI*(hcount%12-15) / 6)); int mx = (int) (90*Math.cos(Math.PI*(mcount-15) / 30)); int my = (int) (90*Math.sin(Math.PI*(mcount-15) / 30)); int sx = (int) (110*Math.cos(Math.PI*(scount-15) / 30)); // -15 是為了調整時差(角度差) int sy = (int) (110*Math.sin(Math.PI*(scount-15) / 30));
最后和畫指針的結合起來進行繪制就可以讓指針動起來。
附加一個功能 顯示上午下午的功能
//繪制 上午下午APMPaint.setTextSize(20);APMPaint.setStrokeWidth(2);canvas.rotate(-30,mWidth/2,mHeight/2);String apm ;if (hcount < 12){ apm = 'AM';}else{ apm = 'PM';} canvas.drawText(apm, mWidth/2-degreePaint.measureText(apm)/2, mHeight/2+100, APMPaint);
大家還可以繼續拓展,添加星期,和每個月的日期,做成一個屬于你自己的表。
效果圖:
參考代碼
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: