Dav
Dav

Reputation: 13

How to fill area between two circle in canvas?

I want to fill area between two circle in canvas enter image description here

this is my ondraw

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

    canvas.drawCircle(centerX, centerY, radarRadius / 3, mPaintCircle);
    canvas.drawCircle(centerX, centerY, 3 * radarRadius / 7, mPaintCircle);
}

Upvotes: 1

Views: 1175

Answers (2)

Yas
Yas

Reputation: 5471

You can use the following simple rule :)

Two nested circles

Sample Code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Two Circles</title>
</head>

<body>
    <canvas id="canvas" width="200" height="200"></canvas>

    <script>
        var canvas = document.getElementById('canvas')
        var ctx = canvas.getContext('2d')

        var cx = 100
        var cy = 100
        var r1 = 80
        var r2 = 60

        // outer circle
        ctx.fillStyle = 'red'
        ctx.beginPath()
        ctx.arc(cx, cy, r1, 0, 2 * Math.PI)
        ctx.fill()

        // inner circle
        ctx.fillStyle = 'white'
        ctx.beginPath()
        ctx.arc(cx, cy, r2, 0, 2 * Math.PI)
        ctx.fill()
    </script>
</body>

</html>

Upvotes: 1

Rohit Arya
Rohit Arya

Reputation: 6791

You can create two circular paths and clip the canvas like this:

Path outerPath = new Path();
outerPath.addCircle(centerX, centerY, outerRadius, Direction.CW);
Path innerPath = new Path();
innerPath.addCircle(centerX, centerY, innerRadius, Direction.CW);
canvas.clipPath(outerPath);
canvas.clipPath(innerPath, Region.Op.DIFFERENCE);

Along with that disable Hardware Acceleration on the view:

view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

Upvotes: 1

Related Questions