美文网首页
给任意布局加圆角

给任意布局加圆角

作者: crush_d872 | 来源:发表于2019-01-24 11:41 被阅读0次
    public class CornersView extends LinearLayout {
    private float roundLayoutRadius;
    private Path roundPath;
    private RectF rectF;
    
    public CornersView(Context context) {
        this(context, null);
    }
    
    public CornersView(Context context, AttributeSet attrs) {
        super(context, attrs);
    
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundLayout);
        roundLayoutRadius = typedArray.getDimensionPixelSize(R.styleable.RoundLayout_roundLayoutRadius, (int) roundLayoutRadius);
        typedArray.recycle();
    
        init();
    }
    
    private void init() {
        setWillNotDraw(false);//如果你继承的是ViewGroup,注意此行,否则draw方法是不会回调的;
        roundPath = new Path();
        rectF = new RectF();
    }
    
    private void setRoundPath() {
        //添加一个圆角矩形到path中, 如果要实现任意形状的View, 只需要手动添加path就行
        roundPath.addRoundRect(rectF, roundLayoutRadius, roundLayoutRadius, Path.Direction.CW);
    }
    
    
    public void setRoundLayoutRadius(float roundLayoutRadius) {
        this.roundLayoutRadius = roundLayoutRadius;
        setRoundPath();
        postInvalidate();
    }
    
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        rectF.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        setRoundPath();
        if (roundLayoutRadius > 0f) {
            canvas.clipPath(roundPath);
        }
        super.onDraw(canvas);
    }
    
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }
    

    }

    如果没有实现圆角,有可能是里面的布局和这一层有padding或者margin值

    相关文章

      网友评论

          本文标题:给任意布局加圆角

          本文链接:https://www.haomeiwen.com/subject/nwjyjqtx.html