Fill intersection area of objects

2019-07-23 17:31发布

问题:

I want to fill the intersection area of a rectangle and a circle using Android Canvas like in the image below:

How can I achieve this?

Update : here my code

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);
    }

}

Now :

in this case, The Wanted result is this :

Thanks for any help

回答1:

You need to look at the android.graphics.Path class.

If you can define your shapes with Paths, then you can draw them using canvas.drawPath().

Path has a method called op() that you can use to get the intersection of two paths, like this:

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

With a Paint.Style of FILL, you can color the intersection of the two shapes.