上一篇《Android 自定义View(一) Paint、Rect、Canvas介绍》讲了最基础的如何自定义一个View,以及View用到的一些工具类。下面讲下View绘制的方法及过程
public class MyView extends View { private String TAG = "--------MyView"; private int width, height; public MyView(Context context, AttributeSet attrs) { super(context, attrs); Log.i(TAG,"MyView()"); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); width = w; height = h; Log.i(TAG,"onSizeChanged()"); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Log.i(TAG,"onDraw()"); Rect rect = new Rect(0, 0, width, height); Paint paint = new Paint(); paint.setColor(Color.RED); canvas.drawRect(rect, paint); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); Log.i(TAG,"onMeasure()"); } @Override protected void onFinishInflate() { super.onFinishInflate(); Log.i(TAG,"onFinishInflate()"); } }
03-15 01:28:53.111 30961-30961/com.myView I/--------MyView: MyView()
03-15 01:28:53.111 30961-30961/com.myView I/--------MyView: onFinishInflate()
03-15 01:28:53.210 30961-30961/com.myView I/--------MyView: onMeasure()
03-15 01:28:53.210 30961-30961/com.myView I/--------MyView: onMeasure()
03-15 01:28:53.520 30961-30961/com.myView I/--------MyView: onMeasure()
03-15 01:28:53.520 30961-30961/com.myView I/--------MyView: onMeasure()
03-15 01:28:53.520 30961-30961/com.myView I/--------MyView: onSizeChanged()
03-15 01:28:53.543 30961-30961/com.myView I/--------MyView: onDraw()
1、MyView() 构造方法,这个不做解释,铁定第一个被调用。
作用:传入Context
2、onFinishInflate() 当View中所有的子控件均被映射成xml后触发
3、onMeasure() 在View放置到父容器时调用
作用:测量View的大小,也可以通过下面方式,修改View的大小
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(100,100); }
也可以通过以下方式获取控件的宽和高
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec)); }
4、onSizeChanged() 在控件大小发生改变时调用。所以这里初始化会被调用一次
作用:获取控件的宽和高度
5、onDraw() 最后就是绘制图形了
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。