Question

I have drawn a circle filled with black color in the canvas and I have set the background color of the canvas to red.

I want only the circle which is black color to appear as my view but I get the red color as well.

I tried using canvas.clipPath() it dint work. I searched the net and found out we need to disable hardware acceleration to get it work. I tried that but it still dint work.

Tried disabling the Hardware Acceleration for particular view:

view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

And also to whole application:

android:hardwareAccelerated="false"

Dint work in both the cases. Any ideas on how to make it work ?

enter image description here

Code:

And here I am clipping

    @Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    this.canvas = canvas;
    path.reset();
    left = 50;
    top = 50;
    right = getWidth()- 50;
    bottom = getHeight()-50;



    RectF rectf = new RectF(left, top, right, bottom);
    path.arcTo(rectf, startAngle, sweepAngle);
    path.lineTo(linex, liney);

    canvas.clipPath(path);
    canvas.drawPath(path, paint);

    //canvas.restore();
}
Was it helpful?

Solution

This is not what clip path is for. When you draw a path and then clip it - it means that the rest of the things you will draw on the canvas from that point will be masked by the path. In your case you draw a red background before clipping the canvas - so it went all over the canvas, then you clipped it but draw only inside the path, so the clipping was useless.

you can get what you need that in that code:

// Do not set any background to the view before
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    this.canvas = canvas;
    path.reset();
    left = 50;
    top = 50;
    right = getWidth()- 50;
    bottom = getHeight()-50;



    RectF rectf = new RectF(left, top, right, bottom);
    path.arcTo(rectf, startAngle, sweepAngle);
    path.lineTo(linex, liney);

    canvas.clipPath(path);
    canvas.drawRect(0, 0, getWidth(), getHeight(), Red Paint in here);
    canvas.drawPath(path, paint);

    //canvas.restore();
}

That way you draw the background after pathClip

You will not see any red color because you draw all over the path right after it, if I am guessing right - you want to be able to draw a part of a circle in one color and the rest in other - you can achieve it if your path that you will clip will be the full circle and the path that you draw will be the part that you want to draw

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top