Search code examples
androidandroid-drawableandroid-glideandroid-color

Android: generate Drawable having resource image and Color


I'm using Glide to load image from url and need to have a placeholder which is generated with a transparent pattern stored as a resource and a random background color. Glide allows using Drawable as a placeholder. I have a transparent drawable resource int resId = R.drawable.placeholder; and have Color randomColor = generateRandomColor(); How can I create a Drawable which is created in combination of resource and background random color, smth. like Drawable d = resId + randomColor; ? To have as a result:

Glide.with(getActivity).load(imageUl)
         .asBitmap().placeholder(d)
         .into(imageView); 

Solution

  • You can use the method setColorFilter of Drawable

    So the code will be like:

    Drawable drawable = getDrawable(resourceId);
    drawable.setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
    
    Glide.with(getActivity).load(imageUl)
             .asBitmap().placeholder(drawable)
             .into(imageView); 
    

    PorterDuff has a lot of modes, choose the one that's right for you