自定义View分类
- 自定义View分为自绘控件和重写控件
- 自绘控件:创建一个类继承view,通过重写OnDraw方法,使用canvas,paint等工具完成绘制,然后在activity的布局中引用
时钟案例
- 首先获取系统时间,然后通过子线程实现每隔1s就将画布旋转一个角度然后重新画一次时针,分针,秒针
- 重写OnDraw方法
@Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setDither(true);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.time);
Rect rect = new Rect(getWidth() / 4, getHeight() / 2 - getWidth() / 4, getWidth() / 4 * 3, getHeight() / 2 + getWidth() / 4);
canvas.drawBitmap(bitmap, null, rect, paint);
paint.setColor(Color.parseColor("#FFE098"));
canvas.save();
canvas.rotate(b*6+c*6/60, getWidth() / 2, getHeight() / 2);
paint.setStrokeWidth(8);
canvas.drawLine(getWidth() / 2, getHeight() / 2, getWidth() / 2, getHeight() / 2 - getWidth() / 4 + 130, paint);
canvas.restore();
canvas.save();
canvas.rotate(a*30+b*30/60, getWidth() / 2, getHeight() / 2);
paint.setStrokeWidth(15);
canvas.drawLine(getWidth() / 2, getHeight() / 2, getWidth() / 2, getHeight() / 2 - getWidth() / 4 + 200, paint);
canvas.restore();
canvas.save();
canvas.rotate(c*6, getWidth() / 2, getHeight() / 2);
paint.setTextSize(50);
paint.setStrokeWidth(5);
canvas.drawLine(getWidth() / 2, getHeight() / 2, getWidth() / 2, getHeight() / 2 - getWidth() / 4 + 60, paint);
canvas.restore();
}
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Time t=new Time();
t.setToNow();
a = t.hour;
b = t.minute;
c = t.second;
Thread.sleep(1000);
postInvalidate();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
<com.example.mytest.MyView
android:layout_width="match_parent"
android:layout_height="match_parent" />