自定义view之继承View重写onDraw方法

来源:互联网 发布:申请网络试听许可证 编辑:程序博客网 时间:2024/05/10 09:08

首先,这种继承方法主要用于实现一些不规则的效果,一般需要重写onDraw方法。

实现view的构造方法

public CircleView(Context context){

super(context);

init();

};

public CircleView(Context context,AttributeSet attrs){

super(context,attrs);

init();

};

在values下新建一个attrs.xml文件

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="CircleView">        <attr name="circle_color" format="color" />    </declare-styleable></resources>

public CircleView(Context context,AttributeSet attrs,int defStyleAttr){

super(context,attrs,defStyleAttr);

//自定义属性,先加载然后解析最后释放

TypedArray a=context.obtainStyledAttributes(attrs,R.styleable.CircleView);

mColor=a.getColor(R.styleable.CircleView_circle_color,Color.RED);

a.recycle();

init();

};

接下来获得画笔对象(Paint mPaint=new Paint(Paint.ANTI_ALIAS_FLAG);去锯齿

int mColor=Color.RED;给画笔设置个颜色)

重写onDraw方法

@Override

protected void onDraw(Canvas canvas){

        super.onDraw(canvas);

//我们要处理padding,不然会是无效的

int paddingLeft=getPaddingLeft();

    int paddingRight=getPaddingRight();

int paddingTop=getPaddingTop();

int paddingBottom=getPaddingBottom();


int width=getWidth();

int height=getHeight();

int radius=Math.min(width,height)/2;

canvas.drawCircle(paddingLeft+width/2,paddingTop+height/2,radius.mPaint);

}

处理wrap_content

  @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);//        widthMeasureSpec = MeasureSpec.makeMeasureSpec((1 << 30) - 1, MeasureSpec.AT_MOST);//        heightMeasureSpec = MeasureSpec.makeMeasureSpec((1 << 30) - 1, MeasureSpec.AT_MOST);//        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);        // 在wrap_content的情况下默认长度为200dp        int minSize = 200;        // wrap_content的specMode是AT_MOST模式,这种情况下宽/高等同于specSize        // 查表得这种情况下specSize等同于parentSize,也就是父容器当前剩余的大小        // 在wrap_content的情况下如果特殊处理,效果等同martch_parent        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {            setMeasuredDimension(minSize, minSize);        } else if (widthSpecMode == MeasureSpec.AT_MOST) {            setMeasuredDimension(minSize, heightSpecSize);        } else if (heightSpecMode == MeasureSpec.AT_MOST) {            setMeasuredDimension(widthSpecSize, minSize);        }    }}



0 0
原创粉丝点击