在开发中,android原生的控件很多时候不能满足产品的设计需求,这个时候我们就需要自己去实现这些效果,而自定义View对很多程序猿的来说还是有点困难的,但这又是高手进阶的必经之路,所以在这里大致了解下自定义view的绘制流程以及步骤:
什么是View
View是Android中所有控件的基类,View是一种界面层的控件的一种抽象,它代表了一个控件,在Android设计中,ViewGroup也继承了View,这就意味着View本身就可以是单个控件也可以是多个控件组成的一组控件,通过这种关系就形成了View树的结构。
View的绘制流程
View的绘制流程是从ViewRoot的performTraversals方法开始的,它经过measure、layout、draw三个过程才能最终将一个View绘制出来,其中measure用来测量View的宽和高,layout用来确定View在父容器的放置位置,而draw则负责将View绘制在屏幕上。
Measure
我们知道View的大小不仅由自身所决定,同时也会受到父控件的影响,为了我们的控件能更好的适应各种情况,View会先进行测量,来算出自己所占用的大小。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthsize = MeasureSpec.getSize(widthMeasureSpec); //取出宽度的确切数值
int widthmode = MeasureSpec.getMode(widthMeasureSpec); //取出宽度的测量模式
int heightsize = MeasureSpec.getSize(heightMeasureSpec); //取出高度的确切数值
int heightmode = MeasureSpec.getMode(heightMeasureSpec); //取出高度的测量模式
}
从上面可以看出 onMeasure 函数中有 widthMeasureSpec 和 heightMeasureSpec 这两个 int 类型的参数,通过MeasureSpec可以得出其原始的SpecMode和SpecSize:
MeasureSpec的理解
MeasureSpec通过将SpecMode和SpecSize打包成一个int值来避免过多的内存分配,为了方便操作,其提供了打包和解包方法。SpecMode和SpecSize也是一个int值,一组SpecMode和SpecSize可以打包为一个MeasureSpec,而一个MeasureSpec可以通过解包的形式来得出其原始的SpecMode和SpecSize。
SpecMode分为三类
UNSPECIFIED 父容器不对View有任何的限制,要多大给多大,这种情况下一般用于系统内部,表示一种测量的状态.
EXACTLY 父容器已经检测出View所需要的精确大小,这个时候View的最终大小就是SpecSize所指定的值,它对应于LayoutParams中的match_parent和具体的数值这两种模式.
AT_MOST 父容器指定了一个可用大小即SpecSize,View的大小不能大于这个值,具体是什么值要看不同View的具体实现。它对应于LayoutParams中的wrap_content.
- Layout
onLayout方法里主要是用来摆放子view的位置,水平摆放或者垂直摆放,一般在在自定义ViewGroup中会用到,所以在单纯的自定义view是不需要重写onLayout方法。
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}
- Draw
onDraw()方法主要是负责绘制内容,需要在这个方法里,用Paint在Canvas上画出你想要的效果。
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
自定义view的步骤:
自定义view的步骤一般由以下几种组成:
自定义View的属性
在View的构造方法中获取我们自定义的属性
重写onMesure(非必须)
重写onDraw
对外提供接口
自定义View的属性
第一步,自定义View的属性。我们首先在res/values/ 下建立一个attrs.xml , 在里面定义我们的属性和声明我们的整个样式。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="firstColor" format="color"/>
<attr name="secondColor" format="color"/>
<attr name="circleWidth" format="dimension"/>
<declare-styleable name="CircleView">
<attr name="firstColor"/>
<attr name="secondColor"/>
<attr name="circleWidth"/>
</declare-styleable>
</resources>
我们定义了圆的第一层,第二层的颜色,和圆的宽度3个属性,format是指该属性的取值类型:
format的取值类型一共有10种:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;
然后在布局文件中声明我们的自定义view
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:circleview="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<cn.lw.view.CircleView
android:layout_width="100dp"
android:layout_height="100dp"
circleview:circleWidth="10dp"
circleview:firstColor="@color/colorPrimary"
circleview:secondColor="@color/colorPrimaryDark"
/>
</RelativeLayout>
在View的构造方法中获取我们自定义的属性
第二步,在View的构造方法中获取我们自定义的属性:
public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView, defStyleAttr, 0);
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.CircleView_firstColor:
mFirstColor = a.getColor(attr, Color.BLACK);
break;
case R.styleable.CircleView_secondColor:
mSecondColor = a.getColor(attr, Color.BLACK);
break;
case R.styleable.CircleView_circleWidth:
mCircleWidth = a.getDimensionPixelSize(attr, (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_PX, 20, getResources().getDisplayMetrics()));
break;
default:
break;
}
}
//回收内存
a.recycle();
}
重写onMesure
第三步,重写onMesure。这里我们重写了onMesure,当然onMeasure不是必须的,在自定义view你可以直接设置固定宽高,不考虑wrap_content情况.
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 获得它的父容器为它设置的测量模式和大小
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int mWidth = 0;
int mHeight = 0;
if (widthMode == MeasureSpec.AT_MOST){
//没有固定宽度,就取默认的宽度
mWidth = (int) dptopx(CIRCLE_SIZE);
}else{
//如果设置了固定的宽度,就取宽高的最小值
mWidth = Math.min(widthSize, heightSize);;
}
if (heightMode == MeasureSpec.AT_MOST){
//没有固定高度,就取默认的高度
mHeight = (int) dptopx(CIRCLE_SIZE);
}else{
//如果设置了固定的高度,就取宽高的最小值
mHeight = Math.min(widthSize, heightSize);;
}
//设置宽高
setMeasuredDimension(mWidth, mHeight);
mPaint = new Paint();
mTextPaint = new Paint();
}
这里重写onMeasure方法,主要是当宽高设置wrap_content时,我们在代码中给个固定的宽高.这里需要注意的是,测量所得的宽高不一定是最后展示的宽高,最终宽高确定是在onLayout方法里,不过一般都是一样的。
重写onDraw
第四步,重写onDraw方法。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mCenter = getWidth() / 2;
mRadius = mCenter - mCircleWidth;
//画圆
drawCircle(canvas);
//绘制进度
drawTextView(canvas);
//换圆弧
drawArc(canvas);
}
private void drawCircle(Canvas canvas) {
//设置圆的宽度
mPaint.setStrokeWidth(mCircleWidth);
//设置画笔的风格
mPaint.setStyle(Paint.Style.STROKE);
// 消除锯齿
mPaint.setAntiAlias(true);
//设置画笔颜色
mPaint.setColor(mFirstColor);
//画圆
canvas.drawCircle(mCenter, mCenter, mRadius, mPaint);
}
private void drawTextView(Canvas canvas) {
mTextPaint.setColor(Color.BLACK);
mTextPaint.setTextSize(sptopx(20.0f));
// 消除锯齿
mTextPaint.setAntiAlias(true);
String text = (int) (100 * ((getProgress() / (1.0f * mMaxProgress))))+ "%";
Rect mTextRect = new Rect();
mTextPaint.getTextBounds(text, 0, text.length(), mTextRect);
//绘制进度
canvas.drawText(text, mCenter - (mTextRect.width() / 2),
mCenter + (mTextRect.height() / 2), mTextPaint);
}
private void drawArc(Canvas canvas) {
mPaint.setColor(mSecondColor);
//画笔的笔触风格(ROUND,表示是圆角的笔触)
mPaint.setStrokeCap(Paint.Cap.ROUND);
float sweepAngle = 360 * (getProgress() / (mMaxProgress * 1.0f));
RectF rect = new RectF(mCenter - mRadius, mCenter - mRadius,
mCenter + mRadius, mCenter + mRadius);
//画圆弧
canvas.drawArc(rect, -90, mProgress, false, mPaint);
}
对外提供接口
通常我们在自定义view的时候一些参数并不是在其中写死,而需要通过外层来调用赋值,这就需要在内部开放对外的方法,比如:
public void setProgress(int progress) {
this.mProgress = progress;
if (mProgress > mMaxProgress || mProgress < 0) {
return;
}
invalidate();
}
public int getProgress() {
return mProgress;
}
然后外层调用
public class MainActivity extends AppCompatActivity {
private CircleView mCircleView;
private boolean flag = true;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
int progress = mCircleView.getProgress();
if (progress < 100) {
mCircleView.setProgress(++progress);
} else
flag = false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCircleView = (CircleView) findViewById(R.id.circleview);
new Thread(new Runnable() {
@Override
public void run() {
while (flag) {
try {
Thread.sleep(100);
mHandler.sendEmptyMessage(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
- 另外这里提下Android的invalidate与postInvalidate的区别:
postInvalidate() 方法在非 UI 线程中调用,通知 UI 线程重绘,即不需要handler,直接在线程中调用postInvalidate即可。
invalidate() 方法在 UI 线程中调用,重绘当前 UI,即它需要实例化一个Handler对象,并重写handleMessage方法调用invalidate()实现界面刷新;而在线程中通过sendMessage发送界面更新消息。
所以上面的MainActivity代码可以不用创建Handler 来更新ui,如下
public class MainActivity extends AppCompatActivity {
private CircleView mCircleView;
private boolean flag = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCircleView = (CircleView) findViewById(R.id.circleview);
new Thread(new Runnable() {
@Override
public void run() {
while (flag) {
try {
Thread.sleep(100);
int progress = mCircleView.getProgress();
if (progress < 100) {
mCircleView.setProgress(++progress);
} else {
flag = false;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
所以setProgress()方法里就不能用invalidate()来更新UI了:
public void setProgress(int progress) {
this.mProgress = progress;
if (mProgress > mMaxProgress || mProgress < 0) {
return;
}
postInvalidate();
}
这样一个完整的自定义view流程就差不多了,效果图如下