android 自定义View绘制计时器


android 自定义View绘制计时器_第1张图片

package com.example.drawView;

import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;

public class Draw_1 extends View {
	
	static Canvas canvas;
	Paint paint;
	Context context;
	int hours=0,minutes=0;
	String HOURS,MINUTES;
	boolean b=true;
	public Draw_1(Context context) {
		super(context);
		this.context=context;
		
                //使用timer每1s重绘一次画面
		Timer timer=new Timer();
		timer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				postInvalidate();//重绘view
				b=!b;
				minutes=minutes+1;
				Log.d("logd", hours+":"+minutes);
				
			}
		}, 1000, 1000);//1秒钟之后开始执行,每1秒钟执行一次
	}

	int COUNT=0;
	protected void onDraw(android.graphics.Canvas canvas) {
		
		this.canvas=canvas;
		canvas.drawColor(Color.WHITE);
		
		paint=new Paint();
		paint.setAntiAlias(true);//去锯齿
		paint.setColor(Color.GRAY);
		paint.setStyle(Paint.Style.STROKE);
		paint.setStrokeWidth(5);	
		
		//获取屏幕分辨率
		DisplayMetrics dMetrics=getResources().getDisplayMetrics();
		
		//画圆角矩形
		paint.setStyle(Paint.Style.FILL);
		RectF rel=new RectF(dMetrics.widthPixels/8, dMetrics.heightPixels/4, 7*dMetrics.widthPixels/8, 2*dMetrics.heightPixels/4);
		canvas.drawRoundRect(rel, 15, 15, paint);
		
		
		
		if (minutes>59) {
			minutes=0;
			hours=hours+1;
		}
		if (hours>59) {
			hours=0;
		}
		//格式化数字,将不足为两位数的数字格式化为类似00,01,02....
		DecimalFormat decimalFormat=new DecimalFormat("00");
		HOURS=decimalFormat.format(hours);
		MINUTES=decimalFormat.format(minutes);


		paint.setColor(Color.GREEN);
		paint.setTextSize(300);
		canvas.drawText(HOURS+"", 5*dMetrics.widthPixels/32 ,55*dMetrics.heightPixels/128, paint);
		canvas.drawText(MINUTES+"", 17*dMetrics.widthPixels/32 ,55*dMetrics.heightPixels/128, paint);
		
		if (b) {
			paint.setColor(Color.GREEN);//显示小圆点
			canvas.drawCircle(16*dMetrics.widthPixels/32 ,46*dMetrics.heightPixels/128, 20, paint);
			canvas.drawCircle(16*dMetrics.widthPixels/32 ,51*dMetrics.heightPixels/128, 20, paint);
		}else {
			paint.setColor(Color.GRAY);//不显示小圆点
			canvas.drawCircle(16*dMetrics.widthPixels/32 ,46*dMetrics.heightPixels/128, 20, paint);
			canvas.drawCircle(16*dMetrics.widthPixels/32 ,51*dMetrics.heightPixels/128, 20, paint);
		}
		
		
		
	};
	

}
最后用一个activity呈现view

package com.example.drawView;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

public class ShowViewDemo extends Activity{

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(new Draw_1(this));		
	
	}
	
	
}


你可能感兴趣的:(Android笔记)