How to preallocate RadialGradient?

岁酱吖の 提交于 2019-12-11 08:17:33

问题


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:


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


来源:https://stackoverflow.com/questions/14872177/how-to-preallocate-radialgradient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!