Custom Layout that rounds the corners of its content

后端 未结 7 2072
北海茫月
北海茫月 2020-11-29 04:08

I would like to create a generic ViewGroup which can then be reused in XML layouts to round the corners of anything that is put into it.

For some reason canvas

7条回答
  •  误落风尘
    2020-11-29 04:45

    You can override the draw(Canvas canvas) method:

    
    
        public class RoundedLinearLayout extends LinearLayout {
            Path mPath;
            float mCornerRadius;
    
            public RoundedLinearLayout(Context context) {
                super(context);
            }
    
            public RoundedLinearLayout(Context context, AttributeSet attrs) {
                super(context, attrs);
            }
    
            public RoundedLinearLayout(Context context, AttributeSet attrs, int defStyle) {
                super(context, attrs, defStyle);
            }
    
            @Override
            public void draw(Canvas canvas) {
                canvas.save();
                canvas.clipPath(mPath);
                super.draw(canvas);
                canvas.restore();
            }
    
            @Override
            protected void onSizeChanged(int w, int h, int oldw, int oldh) {
                super.onSizeChanged(w, h, oldw, oldh);
                RectF r = new RectF(0, 0, w, h);
                mPath = new Path();
                mPath.addRoundRect(r, mCornerRadius, mCornerRadius, Direction.CW);
                mPath.close();
            }
    
            public void setCornerRadius(int radius) {
                mCornerRadius = radius;
                invalidate();
            }
          }
    
    

提交回复
热议问题