自动义View
- 自定义View分类
- 时钟案例
自定义View分类
- 自定义ViewGroup
自定义ViewGroup一般是利用现有的组件根据特定的布局方式来组成新的组件,大多继承自ViewGroup或各种Layout。
- 自定义View
在没有现成的View,需要自己实现的时候,就使用自定义View,一般继承自View,SurfaceView或其他的View。
时钟案例
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();
}
通过子线程实现每隔1s画布转动一个角度,然后重新画时针,分针,秒针。
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;
//隔1s刷新一次
Thread.sleep(1000);
postInvalidate();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();