Fill intersection area of objects

99封情书 提交于 2019-12-07 22:41:10

问题


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.



来源:https://stackoverflow.com/questions/42370178/fill-intersection-area-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!