一.简单的描述自定义控件
自定义控件:
系统的控件满足不了我们的需求,需要自己定义控件。
方式:1.组合方式 (用系统控件拼接功能)
2.继承方式 (在已有的控件基础上添加新的功能)
* 继承于什么
— View 单个控件
— RelativeLayout FrameLayout LinearLayout ViewGroup 多个控件组成
自定义的过程:
3.自绘方式 (自己画内容)
- .Canvas 画布;
- .Path 路径 形状 图形
- .Paint 画笔
- onDraw 具体渲染 画上去
- onMeasure 测量:设置视图控件的具体尺寸
4.简单的例子
效果图:
目录结构:
WaveView的具体代码:
package com.example.pxdwaveview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;
public class WaveView extends View {
public WaveView(Context context) {
super(context);
}
public WaveView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
//Canvas Paint Path;
//创建一个路径
Path mPath = new Path();
//设置路径的起始点
mPath.moveTo(50, 500);
//划线
// mPath.lineTo(400, 700);
//画贝塞尔曲线一
/*
mPath.cubicTo(50, 500, 200, 300,
350, 500);
mPath.cubicTo(350, 500 ,500, 700, 650, 500);*/
mPath.quadTo(200, 300, 350, 500);
mPath.quadTo(500, 700, 650, 500);
Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStrokeWidth(10);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
//绘制
canvas.drawPath(mPath, mPaint);
}
}
在activity.xml使用:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">
<com.example.pxdwaveview.WaveView
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>