填充对象的交叉区域

Fill intersection area of objects

我想使用 Android Canvas 填充矩形和圆形的交叉区域,如下图所示:

我怎样才能做到这一点?

更新: 这是我的代码

public static class MyView extends View {
    private Paint paint;
    public MyView(Context context) {
        super(context);
        init();
    }
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public MyView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }
    private void init() {
        paint = new Paint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(5);
        paint.setColor(Color.BLUE);
        canvas.drawRect(getRect(), paint);
        paint.setColor(Color.GRAY);
        canvas.drawCircle(250,150, 100, paint);
    }

    public Rect getRect() {
        return new Rect(100,100,400,200);
    }

}

现在:

在这种情况下,通缉结果是这样的:

感谢您的帮助

你需要看看 android.graphics.Path class.

如果您可以使用 Path 定义形状,那么您可以使用 canvas.drawPath() 来绘制它们。

Path 有一个名为 op() 的方法,您可以使用它来获取两条路径的交集,如下所示:

    Path square = ...
    Path circle = ...
    Path intersect = circle.op(square, Op.INTERSECT);

使用 Paint.StyleFILL,您可以为两个形状的交叉点着色。