Convert GradientDrawable to Bitmap

前端 未结 3 1117
误落风尘
误落风尘 2021-01-20 03:26

I have the following gradient (generated dynamically):

    GradientDrawable dynamicDrawable = new GradientDrawable();
    dynamicDrawable.setGradientType(Gra         


        
相关标签:
3条回答
  • 2021-01-20 04:10

    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;
    }
    
    0 讨论(0)
  • 2021-01-20 04:13
    • 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
    0 讨论(0)
  • 2021-01-20 04:29

    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;
    }
    
    0 讨论(0)
提交回复
热议问题