Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert GradientDrawable to Bitmap

I have the following gradient (generated dynamically):

    GradientDrawable dynamicDrawable = new GradientDrawable();
    dynamicDrawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);
    dynamicDrawable.setUseLevel(false);
    int colors[] = new int[3];
    colors[0] = Color.parseColor("#711234");
    colors[1] = Color.parseColor("#269869");
    colors[2] = Color.parseColor("#269869");
    dynamicDrawable.setColors(colors);

and I want to set that drawable in a view using onDraw method.

When I want to assign a Drawable to a bitmap I use the casting (BitmapDrawable), but in that case is not possible due the gradientDrawable cannot be cast to BitmapDrawable.

Any idea about how I solve that?

Thanks in advance

like image 960
MarcForn Avatar asked Jul 22 '26 18:07

MarcForn


1 Answers

I finally found the solution from your response. I paste the code for someone could need it:

private Bitmap createDynamicGradient(String color) {
    int colors[] = new int[3];
    colors[0] = Color.parseColor(color);
    colors[1] = Color.parseColor("#123456");
    colors[2] = Color.parseColor("#123456");

    LinearGradient gradient = new LinearGradient(0, 0, 0, 400, Color.RED, Color.TRANSPARENT, Shader.TileMode.CLAMP);
    Paint p = new Paint();
    p.setDither(true);
    p.setShader(gradient);

    Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    canvas.drawRect(new RectF(0, 0, getWidth(), getHeight()), p);

    return bitmap;
}
like image 155
MarcForn Avatar answered Jul 24 '26 08:07

MarcForn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!