一、什么是自定义View
定义:通过直接定义View或者重写View子类实现逻辑的View。
Android系统自带View结构

二、使用自定义View控件
自定义View
- 自绘控件:直接继承View类的方式自绘控件;
- 重写控件:间接继承View子类的重写控件;
- 组合控件:间接继承View子类,将需要用到的原生控件组合到一起。
自绘控件的步骤:
- 新建一个类继承View;
- 实现Listener接口 ;
- 重写构造;
- 重写OnCreate方法;
- Paint 画笔;
- Canvas绘制 ;
- invalidate刷新;
在布局文件中引用。
Paint常用方法及解释
setAntiAlias():设置画笔的锯齿效果 ;
- setColor():设置画笔;
- setARGB():设置画笔ARGB的值;
- setAlpha():设置画笔Alpha的值;
- setStyle():设置画笔的风格(空心或者实心);
- setStrokeWidth():设置空心框的宽度;
- getColor():获取画笔的颜色;
setTextSize():设置字体的尺寸。
Canvas常用方法及解释
drawLine():绘制直线;
- drawCircle:绘制圆形;
- drawBitmap:绘制图形;
- drawRect():绘制矩形;
drawText():绘制字符。
invalidate方法
刷新View的,必须是在UI线程中进行工作。比如在修改某个view的显示时,调用invalidate()才能看到重新绘制的界面。invalidate()的调用是把之前的旧的view从主UI线程队列中踢掉。
简单来说,重复调用onDraw方法。
三、画时钟代码演示
新建一个类clock:
public class Clock extends View {
Paint paint=new Paint();
private int a=0;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
invalidate();
}
};
public Clock(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//半径
int circleRadius=400;
//设置画笔颜色
paint.setColor(Color.BLUE);
//空心圆
paint.setStyle(Paint.Style.STROKE);
//抗锯齿
paint.setAntiAlias(true);
//圆的宽度
paint.setStrokeWidth(10);
//设置圆的坐标,半径,画笔
canvas.drawCircle(getWidth()/2,getHeight()/2,circleRadius,paint);
//刻度宽
paint.setStrokeWidth(2);
paint.setTextSize(35);
for(int i=1;i<=12;i++){
//保存当前画布
canvas.save();
//画出圆中心,第三个参数是圆中心的大小
canvas.drawCircle(getWidth()/2,getHeight()/2,20,paint);
//依次旋转画布,画出每个刻度和对应数字
canvas.rotate(360/12*i,getWidth()/2,getHeight()/2);
//左起,起始位置x坐标,起始位置y坐标,终止位置x坐标,终止位置y坐标,画笔
canvas.drawLine(getWidth()/2,getHeight()/2-circleRadius,getWidth()/2,getHeight()/2-circleRadius+30,paint);
//循环数字的位置
canvas.drawText(String.valueOf(i),getWidth()/2-15,getHeight()/2-circleRadius+70,paint);
//取出保存画布的状态
canvas.restore();
}
canvas.save();
//得到秒针旋转的角度
//指针的位置
canvas.rotate(360/6*a,getWidth()/2,getHeight()/2);
canvas.drawLine(getWidth()/2,getHeight()/2-300,getWidth()/2,getHeight()/2+40,paint);
//旋转画布
canvas.restore();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
new Thread(new Runnable() {
@Override
public void run() {
while (true){
a++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.sendEmptyMessage(a);
}
}
}).start();
return super.onTouchEvent(event);
}
}
在Layout中:
<com.example.myapplication.Clock
android:layout_width="match_parent"
android:layout_height="match_parent" />
效果图:

本文介绍了Android自定义View的概念与分类,包括自绘控件、重写控件和组合控件,并详细展示了自绘控件的具体实现步骤。通过一个画时钟的例子,演示了如何使用Paint和Canvas来绘制复杂的UI元素。
664

被折叠的 条评论
为什么被折叠?



