How to make an ImageView with rounded corners?

前端 未结 30 2543
天涯浪人
天涯浪人 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:13

    I have done by Custom ImageView:

    public class RoundRectCornerImageView extends ImageView {
    
        private float radius = 18.0f;
        private Path path;
        private RectF rect;
    
        public RoundRectCornerImageView(Context context) {
            super(context);
            init();
        }
    
        public RoundRectCornerImageView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        public RoundRectCornerImageView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }
    
        private void init() {
            path = new Path();
    
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            rect = new RectF(0, 0, this.getWidth(), this.getHeight());
            path.addRoundRect(rect, radius, radius, Path.Direction.CW);
            canvas.clipPath(path);
            super.onDraw(canvas);
        }
    }
    

    How to use:

    
    

    Output:

    Hope this would help you.

提交回复
热议问题