一:概括
自定义view的知识点有:
自定义属性,ondraw,onmeasure等,图片混合主要就是对画笔的定义,和对PorterDuffXfermode类的理解;
二:关于自定义属性不说,怕自己讲不好,网上有很多好的教程,推荐鸿翔的博客,简单透彻,就说下onMeasure;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec,heightMeasureSpec);
}
这是系统提供的,它传进的两个参数,熟悉下,然后回顾我们写layout的时候,关于layout的宽高是怎么设置的呢?不外乎三种“wrap_content”,“match_parent”,”确定值”,这也就是系统测量的时候需要处理的三种情况,分别为EXACTLY,AT_MOST,UNSPECIFIED,有关这些尺寸和模式都定义在MeasureSpec中,这是一个view的内部静态类,顺便看下我们怎处理onMeasure吧,
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode =MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height ;
if (widthMode == MeasureSpec.EXACTLY)
{
width = widthSize;
} else
{
//todo
//获取在wrap_content的模式下的view的width
}
if (heightMode == MeasureSpec.EXACTLY)
{
height = heightSize;
} else
{
//todo
//获取在wrap_content的模式下的view的height
}
setMeasuredDimension(width, height);
}
三:关于onDraw想分享之前做水波动画的时候用到的图片混合,
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int saveFlags = Canvas.MATRIX_SAVE_FLAG | Canvas.CLIP_SAVE_FLAG |Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG;
canvas.saveLayer(getWidth()/2-mBound.width()/2,getHeight()/2-mBound.height()/2,getWidth()/2+mBound.width()/2,getHeight()/2+mBound.height()/2,null,saveFlags);
canvas.drawText(text,getWidth()/2-mBound.width()/2,getHeight()/2+mBound.height()/3,paint);
Paint paint3 = new Paint();
paint3.setAntiAlias(true);
paint3.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); canvas.drawBitmap(bmp1,getWidth()/2mBound.width()/2,getHeight()/2-mBound.height()/2,paint3);
paint3.setXfermode(null);
canvas.restore();
}