Search code examples
androidopencvandroid-canvasandroid-graphics

Colour outside a box in Android, while keeping the box transparent?


I have a box in my Android application, which needs to be transparent, while filling the rest of the frame outside the box with a specific colour.

How exactly could this be done in Canvas or OpenCV or any other means?


Solution

  • Here is an example showing a circle with transparent hole you can implement the same using Rectangle instead of circle.

    public class OverlayWithHoleImageView extends ImageView {
    
    private RectF circleRect;
    private int radius;
    
    public OverlayWithHoleImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //In versions > 3.0 need to define layer Type
        if (android.os.Build.VERSION.SDK_INT >= 11)
        {
            setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
    }
    
    public void setCircle(RectF rect, int radius) {
        this.circleRect = rect;
        this.radius = radius;
        //Redraw after defining circle
        postInvalidate();
    }
    
    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if(circleRect != null) {
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(getResources().getColor(android.R.color.black));
            paint.setStyle(Paint.Style.FILL);
            canvas.drawPaint(paint);
    
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
            canvas.drawRoundRect(circleRect, radius, radius, paint);
        }
    }
    

    }

    reference : Medium