How to preallocate RadialGradient?

2019-07-29 05:18发布

I'm drawing some circles on a canvas. I want to apply a radial gradient to each of this circle. I'm currently allocating a new gradient for each circle, but i'm guessing this not a very good idea.

protected void onDraw(Canvas canvas) 
{
    int radius = 6;
    int cx = radius;
    int cy = radius ;

    for(int i = 0; i < nbPage; i++)
    {
        if(i % 12 ==  0 && i > 0) {
            cx = radius;
            cy += 20;
        }

        RadialGradient gradient = new RadialGradient(cx, cy, radius, 0xFFFFFFFF,
                0xFF000000, android.graphics.Shader.TileMode.CLAMP);
        p.setDither(true);
        p.setShader(gradient);

        canvas.drawCircle(cx, cy, radius, p);
        cx += 20; //16px + 4 de marge

    }
}

Is there a solution to preallocate the radial gradient knowing that each circle have the same radius but differents coordinates ?

Thanks

1条回答
你好瞎i
2楼-- · 2019-07-29 05:35

Take the RadialGradient object and draw it to a Bitmap, then proceed to draw that Bitmap to the Canvas for each circle.

Bitmap circleBitmap = Bitmap.create((int) (radius * 2.0f), (int) (radius * 2.0f),
    Bitmap.Config.ARGB_8888);
Canvas tempCanvas = new Canvas(circleBitmap);

RadialGradient gradient = new RadialGradient(cx, cy, radius, 0xFFFFFFFF,
            0xFF000000, android.graphics.Shader.TileMode.CLAMP);
p.setDither(true);
p.setShader(gradient);

tempCanvas.drawCircle(radius, radius, radius, p);

for (int i = 0; i < nbPage; i++)
    canvas.drawBitmap(circleBitmap, cx + (i * 20) - radius, cy - radius, p);
查看更多
登录 后发表回答