在学习安卓群英传自定义控件章节的时候,有一个例子是绘制时钟,在实现了书上的例子后就想看这个时钟能不能动起来。
这里选择延迟一秒发送消息重绘view来实现的动画,对外提供了开启时钟,关闭时钟的方法,当activity执行onResume方法的时候,执行startClock()方法,当移除view或activity执行onStop方法的时候可以执行stopClock()方法。
首先根据view的宽高来确定圆心的位置,并画出一个圆。再通过view高度的一半减去圆的半径,确定刻度的起始位置,选择刻度的长度并绘制出来。然后再刻度下方绘制出数字。最终将画布进行旋转,时钟总共有60个刻度,循环旋转,每次旋转6度即可。
最后是绘制指针,通过计算算出指针对应每个刻度的X,Y坐标并绘制直线。
代码实现
自定义控件的代码:
public class ClockView extends View{ private Paint circlePaint,dialPaint,numberPaint; //view 的宽高 private float mWidth,mHeight; //圆的半径 private float circleRadius; //圆心X,Y坐标 private float circleX,circleY; private int second,minute; private double hour; private Handler handler = new Handler(Looper.getMainLooper()){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if(msg.what==0){ invalidate(); } } }; public ClockView(Context context, AttributeSet attrs) { super(context, attrs); initPaint(); } private void initPaint(){ //刻盘圆,小时刻度,时针和分针的画笔 circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG); circlePaint.setColor(Color.BLACK); circlePaint.setStyle(Paint.Style.STROKE); circlePaint.setStrokeWidth(10); //分钟刻度的画笔 dialPaint = new Paint(Paint.ANTI_ALIAS_FLAG); dialPaint.setColor(Color.BLACK); dialPaint.setStrokeWidth(5); //数字的画笔 numberPaint = new Paint(Paint.ANTI_ALIAS_FLAG); numberPaint.setColor(Color.BLACK); numberPaint.setStrokeWidth(5); numberPaint.setTextSize(30); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mWidth = getMeasuredWidth(); mHeight = getMeasuredHeight(); if(mWidth
public class Point {
private float x;
private float y;
public Point(float x, float y) { this.x = x; this.y = y; } public float getX() { return x; } public void setX(float x) { this.x = x; } public float getY() { return y; } public void setY(float y) { this.y = y; }
Acitivity:
public class ClockActivity extends Activity{ private ClockView clockView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.clock_layout); clockView = (ClockView) findViewById(R.id.clock); } @Override protected void onResume() { super.onResume(); clockView.startClock(); } @Override protected void onStop() { super.onStop(); clockView.stopClock(); } }
xml布局:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。