一、什么是自定义View?
通过直接继承View或者重写View子类实现逻辑的View,称之为自定义View。
二、如何使用自定义View?
自绘控件:直接继承View类的方式自绘控件;
重写控件:间接继承View子类的方式重写控件;
组合控件:间接继承View子类,将需要用到的原生控件组合到一起。
三、自绘控件的步骤
1、新建类继承View;
2、实现Listener接口;
3、重写构造方法;
4、重写onDraw方法;
onDraw方法:子类需要重写父类的绘制方法;在自绘控件中,绘制的逻辑几乎全部写在这个方法中;此方法需要调好Paint,将Paint画在Canvas上,输出到屏幕上。
5、Paint画笔;
方法:setAntiAlias() 设置画笔的锯齿效果; setStyle() 设置画笔的风格 ;setColor() 设置画笔的颜色;
setStrokeWidth() 设置空心边框的宽度; setARGB() 设置画笔的A R G B值; getColor() 获取画笔颜色;
setAlpha() 设置画笔的Alpha值; setTextSize() 设置字体的尺寸。
6、Canvas绘制;
方法:drawLine() 绘制直线; drawRect() 绘制矩形; drawCircle() 绘制圆形; drawText() 绘制字符;
drawBirmap() 绘制图形。
7、invalidate方法刷新;
8、在布局文件中引用。
四、计数器实例
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.homework.activity.viewdemo.MainActivity">
<com.homework.activity.viewdemo.MyView
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
ActivityMain代码:
public class MyView extends View{
private Paint paint=new Paint();
private int num=0;
//第一个参数:上下文环境
//第二个参数,属性集合,接收textsize类属性
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
//绘制
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.RED);
//调用父View的onDraw函数,因为View这个类帮我们实现了一些
//基本的绘制功能,比如绘制背景颜色、背景图片等
int r=getWidth()/4;
int centreX=getWidth()/2;
int centreY=getHeight()/2;
paint.setAntiAlias(true);//反锯齿
//开始绘制
canvas.drawCircle(centreX,centreY,r,paint);
//画笔操作
paint.setColor(Color.BLUE);
paint.setTextSize(50);
//在画布上添加字
canvas.drawText(num+"",centreX-15,centreY+25,paint);//由于字是由左下角为中心,所以要进行微调
paint.setStyle(Paint.Style.FILL);
}
//点击画布时的操作
@Override
public boolean onTouchEvent(MotionEvent event) {
num++;
invalidate();//默认直接调用onDraw方法
return super.onTouchEvent(event);
}
}