在Android画布上绘制路径或形状的交集

时间:2014-03-27 14:13:46

标签: android canvas path intersection

如何绘制两个矩形和路径的交点。看看这张图片。enter image description here

图1是我现在拥有的。图2是我想要实现的目标。这是我的观点代码:

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

1 个答案:

答案 0 :(得分:2)

此代码将绘制图片#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);
}