How to make an ImageView with rounded corners?

前端 未结 30 2598
天涯浪人
天涯浪人 2020-11-21 05:39

In Android, an ImageView is a rectangle by default. How can I make it a rounded rectangle (clip off all 4 corners of my Bitmap to be rounded rectangles) in the ImageView?

30条回答
  •  眼角桃花
    2020-11-21 06:19

    Why not do clipping in draw()?

    Here is my solution:

    • Extend RelativeLayout with clipping
    • Put ImageView (or other views) into the layout:

    Code:

    public class RoundRelativeLayout extends RelativeLayout {
    
        private final float radius;
    
        public RoundRelativeLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
    
            TypedArray attrArray = context.obtainStyledAttributes(attrs,
                    R.styleable.RoundRelativeLayout);
            radius = attrArray.getDimension(
                    R.styleable.RoundRelativeLayout_radius, 0);
        }
    
        private boolean isPathValid;
        private final Path path = new Path();
    
        private Path getRoundRectPath() {
            if (isPathValid) {
                return path;
            }
    
            path.reset();
    
            int width = getWidth();
            int height = getHeight();
            RectF bounds = new RectF(0, 0, width, height);
    
            path.addRoundRect(bounds, radius, radius, Direction.CCW);
            isPathValid = true;
            return path;
        }
    
        @Override
        protected void dispatchDraw(Canvas canvas) {
            canvas.clipPath(getRoundRectPath());
            super.dispatchDraw(canvas);
        }
    
        @Override
        public void draw(Canvas canvas) {
            canvas.clipPath(getRoundRectPath());
            super.draw(canvas);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    
            int oldWidth = getMeasuredWidth();
            int oldHeight = getMeasuredHeight();
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
            int newWidth = getMeasuredWidth();
            int newHeight = getMeasuredHeight();
            if (newWidth != oldWidth || newHeight != oldHeight) {
                isPathValid = false;
            }
        }
    
    }
    

提交回复
热议问题