ImageView in circular through xml

前端 未结 27 1462
死守一世寂寞
死守一世寂寞 2020-11-22 10:35

I\'d Like to make any image from my ImageView to be circular with a border.

I searched but couldn\'t find any useful information (anything that I tried

27条回答
  •  甜味超标
    2020-11-22 10:42

    Create a CustomImageview then simply override its onDraw() method follows:

    @Override
    protected void onDraw(Canvas canvas) {
    
        float radius = this.getHeight()/2;
        Path path = new Path();
        RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());
        path.addRoundRect(rect, radius, radius, Path.Direction.CW);
        canvas.clipPath(path);
        super.onDraw(canvas);
    
    }
    

    In case you want the code for the custom widget as well:-

    CircularImageView.java

    import android.content.Context;
    import android.content.res.TypedArray;
    import android.graphics.Canvas;
    import android.graphics.Path;
    import android.graphics.RectF;
    import android.graphics.drawable.Drawable;
    import android.util.AttributeSet;
    import android.widget.ImageView;
    
    import androidx.annotation.Nullable;
    
    public class CircularImageView extends ImageView {
    
        private Drawable image;
    
        public CircularImageView(Context context) {
            super(context);
    
            init(null, 0);
        }
    
        public CircularImageView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
    
            init(attrs, 0);
        }
    
        public CircularImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
    
            init(attrs, defStyleAttr);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
    
            float radius = this.getHeight()/2;
            Path path = new Path();
            RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());
            path.addRoundRect(rect, radius, radius, Path.Direction.CW);
            canvas.clipPath(path);
            super.onDraw(canvas);
    
        }
    
        private void init(AttributeSet attrs, int defStyle) {
            TypedArray a = Utils.CONTEXT.getTheme().obtainStyledAttributes(attrs, R.styleable.CircularImageView, 0, 0);
            try {
                image = a.getDrawable(R.styleable.CircularImageView_src);
            } finally {
                a.recycle();
            }
    
            this.setImageDrawable(image);
        }
    }
    

    Also, add the following code to your res/attrs.xml to create the required attribute:-

    
            
    
    

提交回复
热议问题