How to make a view with rounded corners?

前端 未结 20 1376
遇见更好的自我
遇见更好的自我 2020-11-27 11:08

I am trying to make a view in android with rounded edges. The solution I found so far is to define a shape with rounded corners and use it as the background of that view.

20条回答
  •  不知归路
    2020-11-27 11:30

    public class RoundedCornerLayout extends FrameLayout {
        private double mCornerRadius;
    
        public RoundedCornerLayout(Context context) {
            this(context, null, 0);
        }
    
        public RoundedCornerLayout(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
        }
    
        public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init(context, attrs, defStyle);
        }
    
        private void init(Context context, AttributeSet attrs, int defStyle) {
            DisplayMetrics metrics = context.getResources().getDisplayMetrics();
            setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
    
        public double getCornerRadius() {
            return mCornerRadius;
        }
    
        public void setCornerRadius(double cornerRadius) {
            mCornerRadius = cornerRadius;
        }
    
        @Override
        public void draw(Canvas canvas) {
            int count = canvas.save();
    
            final Path path = new Path();
            path.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), (float) mCornerRadius, (float) mCornerRadius, Path.Direction.CW);
            canvas.clipPath(path, Region.Op.REPLACE);
    
            canvas.clipPath(path);
            super.draw(canvas);
            canvas.restoreToCount(count);
        }
    }
    

提交回复
热议问题