(Android)画个钟看看

画个钟,用Android

package net.tianyu.android.clock;

import java.util.Calendar;
import java.util.TimeZone;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.RelativeLayout;

public class AndroidClock extends Activity {
	private HourView hourView;
	private Handler hourHandler;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		RelativeLayout absLayout = new RelativeLayout(this);

		hourView = new HourView(this);
		hourHandler = new Handler();
		hourHandler.post(updateHour);
		absLayout.addView(hourView, new RelativeLayout.LayoutParams(416, 416));

		setContentView(absLayout);
	}

	private Runnable updateHour = new Runnable() {
		public void run() {
			hourView.update();
			hourHandler.postDelayed(updateHour, 1000);
		}
	};

	class HourView extends View {

		Matrix mHourMatrix = new Matrix();
		Matrix mMinuteMatrix = new Matrix();
		Bitmap mBmpHour;
		Bitmap mBmpMinute;
		Bitmap mBmpBackground;

		int mWidth = 173;
		int mHeight = mWidth;
		int centerX = 145;
		int centerY = 200;

		public HourView(Context context) {
			super(context);
			mBmpHour = BitmapFactory.decodeResource(getResources(), R.drawable.hour);
			mBmpMinute = BitmapFactory.decodeResource(getResources(), R.drawable.minute);
			mBmpBackground = BitmapFactory.decodeResource(getResources(), R.drawable.background);
		}

		public void update() {
			postInvalidate();
		}

		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);
			Paint p = new Paint();
			p.setColor(Color.RED);

			Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+9:00"));
			int hour = cal.get(Calendar.HOUR);
			int minute = cal.get(Calendar.MINUTE);
			float hourRotate = 270.0f + hour * 30.0f + minute / 60.0f * 30.0f;
			float minuteRotate = 270.0f + minute * 6.0f;

			canvas.drawBitmap(mBmpBackground, 0, 0, p);

			mHourMatrix.postRotate(hourRotate, 17, 7);
			mMinuteMatrix.postRotate(minuteRotate, 17, 7);
			mHourMatrix.postTranslate(centerX, centerY);
			mMinuteMatrix.postTranslate(centerX, centerY);

			canvas.drawBitmap(mBmpHour, mHourMatrix, p);
			canvas.drawBitmap(mBmpMinute, mMinuteMatrix, p);

			mHourMatrix.postTranslate(-1 * centerX, -1 * centerY);
			mMinuteMatrix.postTranslate(-1 * centerX, -1 * centerY);
			mHourMatrix.postRotate(-1.0f * hourRotate, 17, 7);
			mMinuteMatrix.postRotate(-1.0f * minuteRotate, 17, 7);
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值