Search code examples
androidcanvasimageviewdrawpaint

How to draw a rectangle with black border and background transparent on Imageview?


I would like to draw a rectangle on an ImageView as a picture below (black border and transparent as background). Basically I download an Image, put in in a ImageView and after I receive 4 points to draw a rectangle. Thanks in advance

enter image description here


Solution

  • Your problem for android.view.InflateException can be solved by deleting the constructors from DrawView class and auto generate them again. Now for the rectangle you have to have the onDraw similar like this:

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    
        Paint paint = new Paint();
        paint.setColor(Color.TRANSPARENT);
        paint.setStyle(Paint.Style.FILL);
        float leftx = 50;
        float topy =  50;
        float rightx =  150;
        float bottomy =  150;
        // FILL
        canvas.drawRect(leftx, topy, rightx, bottomy, paint);
    
        paint.setStrokeWidth(10);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.STROKE);
        // BORDER
        canvas.drawRect(leftx, topy, rightx, bottomy, paint);
    }
    

    If you want to get the coordinates on click an then draw the rectangle override the onTouchEvent method and do something like this

    class DrawView extends ImageView {
    
        float x, y;
        float width = 60.0f;
        float height = 50.0f;
        boolean touched = false;
    
        public DrawView(Context context) {
            super(context);
        }
    
        public DrawView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public DrawView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        public void onDraw(Canvas canvas) {
            super.onDraw(canvas);
    
    
            if (touched) {
                Paint paint = new Paint();
                paint.setColor(Color.TRANSPARENT);
                paint.setStyle(Paint.Style.FILL);
                // FILL
                canvas.drawRect(x, y, (x + width) / 0.5f, (y + height) / 0.5f, paint);
    
                paint.setStrokeWidth(10);
                paint.setColor(Color.BLACK);
                paint.setStyle(Paint.Style.STROKE);
                // BORDER
                canvas.drawRect(x, y, (x + width) / 0.5f, (y + height) / 0.5f, paint);
            }
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            touched = true;
            //getting the touched x and y position
            x = event.getX();
            y = event.getY();
            invalidate();
            return true;
        }
    
    }