利用canvas.clipPath创建不规则布局

实现效果

利用canvas.clipPath创建不规则布局_第1张图片

 

继承LinearLayout

为了使控件画出外边缘,重写onMeasure方法,使控件高度稍微高出一块,此处取5,也可以通过自定义属性来设置,在onMeasure方法中还有算出较矮子控件高度和较高子控件的高度,高度用于在onDraw中在合适的位置画出边界。

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int height = MeasureSpec.getSize(heightMeasureSpec);

        super.onMeasure(widthMeasureSpec, height+5);

        for(int i=0;i maxHeight) {
                maxHeight = child.getMeasuredHeight();
            }

            if (child.getMeasuredHeight() < minHeight) {
                minHeight = child.getMeasuredHeight();
            }
        }
    }

重写onDraw方法,先用path画出外边框,再用clipPath剪裁布局

 @Override
    public void draw(Canvas canvas) {
        
        Paint paint = new Paint();
        paint.setStrokeWidth(2);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.BLACK);

        int padding = getPaddingLeft();

        Path path = new Path();
        path.moveTo(0,maxHeight-minHeight);
        path.lineTo((getWidth()/2)-(maxHeight-minHeight)-padding,maxHeight-minHeight);
        RectF oval = new RectF( (getWidth()/2)-(maxHeight-minHeight)-padding,0,
                (getWidth()/2)+(maxHeight-minHeight)+padding, (maxHeight-minHeight)*2);
        path.addArc(oval,-180,180);
        path.lineTo(getWidth(),maxHeight-minHeight);
        path.lineTo(getWidth(),getHeight());
        path.lineTo(0,getHeight());
        path.lineTo(0,maxHeight-minHeight);

//        canvas.drawPath(path,paint);
        canvas.clipPath(path);
        super.draw(canvas);

    }

使用



            

                

                

            

            

                

                

            

            

                

                

            

        

 

你可能感兴趣的:(android笔记)