How to make an ImageView with rounded corners?

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

    My implementation of ImageView with rounded corners widget, that (down||up)sizes image to required dimensions. It utilizes code form CaspNZ.

    public class ImageViewRounded extends ImageView {
    
        public ImageViewRounded(Context context) {
            super(context);
        }
    
        public ImageViewRounded(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public ImageViewRounded(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            BitmapDrawable drawable = (BitmapDrawable) getDrawable();
    
            if (drawable == null) {
                return;
            }
    
            if (getWidth() == 0 || getHeight() == 0) {
                return; 
            }
    
            Bitmap fullSizeBitmap = drawable.getBitmap();
    
            int scaledWidth = getMeasuredWidth();
            int scaledHeight = getMeasuredHeight();
    
            Bitmap mScaledBitmap;
            if (scaledWidth == fullSizeBitmap.getWidth() && scaledHeight == fullSizeBitmap.getHeight()) {
                mScaledBitmap = fullSizeBitmap;
            } else {
                mScaledBitmap = Bitmap.createScaledBitmap(fullSizeBitmap, scaledWidth, scaledHeight, true /* filter */);
            }
    
            Bitmap roundBitmap = ImageUtilities.getRoundedCornerBitmap(getContext(), mScaledBitmap, 5, scaledWidth, scaledHeight,
                    false, false, false, false);
            canvas.drawBitmap(roundBitmap, 0, 0, null);
    
        }
    
    }
    

提交回复
热议问题