Android - Set a border around an ImageView

前端 未结 9 1522
旧时难觅i
旧时难觅i 2021-02-06 23:50

I have a cell with a fixed width and height, let it be 100x100px. Inside that cell I want to display an ImageView with a border around.
My first idea was to put

9条回答
  •  耶瑟儿~
    2021-02-07 00:18

    you can use the custom imageview, from where you can get the border, here is the code. you can also change the width of padding and stroke width according to your need. It is specify just below the first line of code, thank you

    public class FreeCollage extends ImageView {
    
        private static final int PADDING = 8;
        private static final float STROKE_WIDTH = 5.0f;
    
        private Paint mBorderPaint;
    
        public FreeCollage(Context context) {
            this(context, null);
        }
    
        public FreeCollage(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
            setPadding(PADDING, PADDING, PADDING, PADDING);
        }
    
        public FreeCollage(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            initBorderPaint();
        }
    
        private void initBorderPaint() {
            mBorderPaint = new Paint();
            mBorderPaint.setAntiAlias(true);
            mBorderPaint.setStyle(Paint.Style.STROKE);
            mBorderPaint.setColor(Color.WHITE);
            mBorderPaint.setStrokeWidth(STROKE_WIDTH);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            canvas.drawRect(PADDING, PADDING, getWidth() - PADDING, getHeight() - PADDING, mBorderPaint);
        }
    }
    

提交回复
热议问题