How to make an ImageView with rounded corners?

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

    Here is a simple example overriding imageView, you can then also use it in layout designer to preview.

    public class RoundedImageView extends ImageView {
    
        public RoundedImageView(Context context) {
            super(context);
        }
    
        public RoundedImageView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public RoundedImageView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public RoundedImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }
    
        @Override
        public void setImageDrawable(Drawable drawable) {
            float radius = 0.1f;
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            RoundedBitmapDrawable rid = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
            rid.setCornerRadius(bitmap.getWidth() * radius);
            super.setImageDrawable(rid);
        }
    }
    

    This is for fast solution. Radius is used on all corners and is based of percentage of bitmap width.

    I just overrided setImageDrawable and used support v4 method for rounded bitmap drawable.

    Usage:

    
    

    Preview with imageView and custom imageView:

提交回复
热议问题