Shnkc
Shnkc

Reputation: 2158

How to fill outside of a drawing on canvas

For some drawn lines on canvas, I want to fill out of it with a color. Where I have come sofar, is following :

int height = getMeasuredHeight();
int width = getMeasuredWidth();
canvas.drawRect(0,0,width, height, mBackgroundPaint);
for(ArrayList<PointF> arc : drawings) {
    Iterator<PointF> iter = arc.iterator();
    Path tempPath = new Path();
    PointF p = iter.next();
    tempPath.moveTo(p.x, p.y);
    while (iter.hasNext()) {
        PointF l = iter.next();
        tempPath.quadTo(p.x, p.y, l.x, l.y);
        p = l;
    }
    tempPath.lineTo(p.x, p.y);
    canvas.drawPath(tempPath, paint);
}

In this code, some custom draw in Arraylist is being drawn. It is drawn by tempPath. The background is filled with color by drawing a filled rectangle. The problem here is if tempPath is drawn and filled by color transparent, background color will be shown. I want to exlude points in tempPath from the background rectangle.

Thanks for your help

Upvotes: 0

Views: 1292

Answers (1)

Shnkc
Shnkc

Reputation: 2158

I have found a way to achieve my goal. This is the code:

int height = getMeasuredHeight();
int width = getMeasuredWidth();
Path backpath = new Path();
backpath.moveTo(0, 0);
backpath.lineTo(0, width);
backpath.lineTo(height, width);
backpath.lineTo(height, 0);
backpath.setFillType(Path.FillType.EVEN_ODD);
for(ArrayList<PointF> arc : drawings) {
    Iterator<PointF> iter = arc.iterator();
    Path tempPath = new Path();
    PointF p = iter.next();
    tempPath.moveTo(p.x, p.y);
    while (iter.hasNext()) {
        PointF l = iter.next();
        tempPath.quadTo(p.x, p.y, l.x, l.y);
        p = l;
    }
    tempPath.lineTo(p.x, p.y);
    backpath.addPath(tempPath);
    canvas.drawPath(path, mBackgroundPaint);
    canvas.drawPath(tempPath, paint);
}

Path.FillType.EVEN_ODD does the work here. I have used two paths. First one is for real drawing, tempPath. Second one is to draw background color, backpath.After drawing bounds, I have added a copy of tempPath into backpath. By setting appropriate paint style, I get the following result:

enter image description here

Upvotes: 1

Related Questions