Convert GradientDrawable to Bitmap

雨燕双飞 提交于 2019-11-28 09:48:09

问题


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


回答1:


  • Create a mutable bitmap using Bitmap.createBitmap()
  • Create a Canvas based on the bitmap using new Canvas(bitmap)
  • Then call draw(canvas) on your GradientDrawable



回答2:


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



回答3:


You can use below code mention in: Android: Convert Drawable to Bitmap

public Bitmap convertToBitmap(Drawable drawable, int widthPixels, int heightPixels) {
    Bitmap mutableBitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(mutableBitmap);
    drawable.setBounds(0, 0, widthPixels, heightPixels);
    drawable.draw(canvas);

    return mutableBitmap;
}


来源:https://stackoverflow.com/questions/33181417/convert-gradientdrawable-to-bitmap

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