Egis
Egis

Reputation: 5141

Draw intersection of paths or shapes on android canvas

How do I draw intersection of two rectangles and path. Look at this image.enter image description here

Picture 1 is what I have now. Picture 2 is what I want to achieve. This is the code of my view:

public class MyView extends View {

    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Paint paintRectA = new Paint();
        Paint paintRectB = new Paint();
        Paint paintPath = new Paint();

        paintRectA.setColor(Color.BLUE);
        paintRectB.setColor(Color.RED);
        paintPath.setColor(Color.CYAN);

        RectF rectA = new RectF(0, 0, 50, 100);
        RectF rectB = new RectF(50, 0, 100, 100);

        Path path = new Path();
        path.lineTo(100, 0);
        path.quadTo(50, 100, 0, 0);
        path.close();

        canvas.drawRect(rectA, paintRectA);
        canvas.drawRect(rectB, paintRectB);
        canvas.drawPath(path, paintPath);
    }
}

Upvotes: 1

Views: 1525

Answers (1)

Egis
Egis

Reputation: 5141

This code will draw picture #2

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    RectF rectA = new RectF(0, 0, 150, 300);
    RectF rectB = new RectF(150, 0, 300, 300);

    Path path = new Path();
    path.lineTo(300, 0);
    path.quadTo(150, 300, 0, 0);
    path.close();

    Bitmap bmp = Bitmap.createBitmap(300, 300, Bitmap.Config.ARGB_8888);
    Canvas bitmapCanvas = new Canvas(bmp);

    Paint paintPath = new Paint(Paint.ANTI_ALIAS_FLAG);
    bitmapCanvas.drawPath(path, paintPath);

    Paint paint = new Paint();
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));

    paint.setColor(Color.BLUE);
    bitmapCanvas.drawRect(rectA, paint);

    paint.setColor(Color.RED);
    bitmapCanvas.drawRect(rectB, paint);

    paint.setXfermode(null);
    canvas.drawBitmap(bmp, 0, 0, paint);
}

Upvotes: 3

Related Questions