效果
思路
- 先繪制刻度和文字梢睛,通過旋轉畫布來操作
//移動畫布到屏幕正中間
canvas.translate(getMeasuredWidth() / 2, getMeasuredHeight() / 2);
//當前數字
int currentP = 0;
//繪制的數字
String text = "";
int len;
for (int i = 0; i < 360 / fixAngle; i++) {
if (i % 5 == 0) {
if (currentP == 0) {
text = "12";
} else {
text = currentP + "";
}
currentP++;
mArcPaint.setColor(Color.BLUE);
mArcPaint.setTextSize(40);
mArcPaint.getTextBounds(text, 0, text.length(), mTextBound);
canvas.drawText(text, 0, text.length(), -mTextBound.width() / 2, -(radius + b_len + 20), mArcPaint);
mArcPaint.setColor(Color.RED);
len = b_len;
} else {
mArcPaint.setColor(Color.GREEN);
len = s_len;
}
canvas.drawLine(0, -radius, 0, -(radius + len), mArcPaint);
//旋轉畫布
canvas.rotate(fixAngle);
}
- 繪制指針
/**
* 畫秒針
* @param canvas
*/
private void drawS(Canvas canvas) {
double angle = (s * fixAngle - 90)*Math.PI/180;
int mSecondLen = 280;
int startX = -(int) (len * Math.cos(angle));
int startY = -(int) (len * Math.sin(angle));
int endX = (int) ((mSecondLen - len) * Math.cos(angle));
int endY = (int) ((mSecondLen - len) * Math.sin(angle));
canvas.drawLine(startX, startY, endX, endY, sPaint);
}
/**
* 畫分針
* @param canvas
*/
private void drawM(Canvas canvas) {
double angle = (m * 6 - 90)*Math.PI/180;
int mMinLen = 250;
int startX = -(int) (len * Math.cos(angle));
int startY = -(int) (len * Math.sin(angle));
int endX = (int) ((mMinLen - len) * Math.cos(angle));
int endY = (int) ((mMinLen - len) * Math.sin(angle));
canvas.drawLine(startX, startY, endX, endY, minPaint);
}
/**
* 畫時針
* @param canvas
*/
private void drawH(Canvas canvas) {
double angle = (h * 6 * 5 - 90)*Math.PI/180+((m *1.0f/60 *30)*Math.PI/180);
int mHourLen = 230;
int startX = -(int) (len * Math.cos(angle));
int startY = -(int) (len * Math.sin(angle));
int endX = (int) ((mHourLen - len) * Math.cos(angle));
int endY = (int) ((mHourLen - len) * Math.sin(angle));
canvas.drawLine(startX, startY, endX, endY, hPaint);
}
- 繪制中心原點
private void drawPoint(Canvas canvas) {
mArcPaint.setColor(Color.WHITE);
canvas.drawCircle(0, 0, 10, mArcPaint);
}
遇到的問題
怎么實時刷新時間 讓指針轉起來绝葡?
方案一
- 繼承自View
- 開線程,添加一個循環(huán)腹鹉,然后通過
handler
去調用invalidate()
結果:打開界面幾秒后 app 直接崩潰
方案二
- 繼承自View
- 在
onDraw()
內加入以下代碼
@Override
protected void onDraw(Canvas canvas) {
.....
postInvalidateDelayed(1000);
invalidate();
}
結果:其實就是一個死循環(huán),效果是出來了愉阎,但是內存抖動特別厲害,頻繁的觸發(fā)GC力奋,
去掉代碼 invalidate(); 后可以正常出效果,內存也正常景殷。
方案三
- 繼承自 SurfaceView
- 緩存一個圖層
private void drawUI() {
try {
canvas = mSurfaceHolder.lockCanvas();
//緩存一個圖層
if (bitmapCache == null) {
bitmapCache = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_4444);
}
canvas1 = new Canvas(bitmapCache);
canvas1.drawColor(Color.BLACK);
drawCanvas(canvas1);
canvas.drawBitmap(bitmapCache, 0, 0, mPaint);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
mSurfaceHolder.unlockCanvasAndPost(canvas);
} catch (Exception e) {
e.printStackTrace();
}
}
}
結果:實現效果澡屡,內存也還比較穩(wěn)定