Android进阶之路Android开发经验谈Android开发

android 圆角的webview

2019-05-10  本文已影响30人  静染星辰

近期根据设计需求需要实现一个上边左右有圆角的webview,如图:

直接上代码:

public class RoundWebview extends WebView{

    float width,height =0;

    private int radius =0;

    public RoundWebview(Context context) {

        super(context);//此处必需引用父控件的构造方法,以使用父控件的主题,否则会造成键盘的一些问题(具体的忘记了,大家可以试试)

    }

public RoundWebview(Context context, AttributeSet attrs) {

        super(context, attrs);//此处必需引用父控件的构造方法,以使用父控件的主题,否则会造成键盘的一些问题(具体的忘记了,大家可以试试)

    }

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

        super(context, attrs, defStyleAttr);//此处必需引用父控件的构造方法,以使用父控件的主题,否则会造成键盘的一些问题(具体的忘记了,大家可以试试)

    }

@Override

    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {

        super.onLayout(changed, left, top, right, bottom);

        width = getWidth();

        height = getHeight() + StatusBarUtil.getBottomStatusHeight(getContext()) +                            StatusBarUtil.getBottomStatusHeight(getContext());

}

public void setRadius(int radius) {

        this.radius = radius;

        invalidate();

    }

    @Override

    protected void onDraw(Canvas canvas) {

        float y =this.getScrollY();//因为webview是可滚动的,所以它的高度是变化的,每个height地方都需要加上滚动值。不加的话控件的高度不能变更,此圆角构成方法适用于其他的控件,如Imageview,此时无需加y.

        int r = StatusBarUtil.dp2px(getContext(),radius);

        if (width > r &&height > r) {

            Path path = new Path();

            path.moveTo(r, 0);

            path.lineTo(width - r, 0);

            path.quadTo(width, 0, width, r);

            path.lineTo(width,y+ height - r);//1,r改为0

            path.quadTo(width, y+ height, width - r, y+ height); //2,r改为0

            path.lineTo(r, y+ height);//3,r改为0

            path.quadTo(0, height, 0, y+ height - r); //4,r改为0  这四处r改为0即可实现上左上右为圆角,否则四角皆为圆角

            path.lineTo(0, r);

            path.quadTo(0, 0, r, 0);

            if(r >0) {

                canvas.clipPath(path);//将路径闭合构成控件的区域

            }

    }

      super.onDraw(canvas);

    }

}

上一篇 下一篇

猜你喜欢

热点阅读