Various View shapes can be realized by using canvas provided by Android API level 1. Isn't the general usage such as generating a View such as a circle or a rectangle or cutting a Bitmap? So this time, I would like to introduce how to ** hollow out the View **.
public class CanvasView extends View {
    private Paint paint = new Paint();
    public CanvasView(Context context) {
        super(context);
    }
    public CanvasView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
    public CanvasView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(getRootView().getWidth() / 2, getRootView().getHeight() / 2, 50, paint);
    }
}
 
public class CanvasView extends View {
    private Paint backgroundPaint = new Paint();
    private Paint paint = new Paint();
    public CanvasView(Context context) {
        super(context);
    }
    public CanvasView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
    public CanvasView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        setLayerType(View.LAYER_TYPE_HARDWARE, null);
        //Draw the whole
        backgroundPaint.setColor(ContextCompat.getColor(getContext(), android.R.color.background_dark));
        canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), backgroundPaint);
        //Hollow out a circle from the whole background
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, 250, paint);
    }
}
 
I created a library using the method introduced here. If you like it, I would be grateful if you could give it a star.
https://github.com/TakuSemba/Spotlight

Recommended Posts