Mike Spike Mike Spike - 1 year ago 240
Android Question

Android Glide load picture file apply overlay and set to imageview

I have image files(png/jpg). When loading to listview, some of them I need to overlay with another transparent image. I do this using something like the following:

public Bitmap applyOverlay(Context context, Bitmap sourceImage, int overlayDrawableResourceId){
Bitmap bitmap = null;
int width = sourceImage.getWidth();
int height = sourceImage.getHeight();
Resources r = context.getResources();
Drawable imageAsDrawable = new BitmapDrawable(r, sourceImage);
Drawable[] layers = new Drawable[2];
layers[0] = imageAsDrawable;
layers[1] = new BitmapDrawable(r, BitmapUtils.decodeSampledBitmapFromResource(r, overlayDrawableResourceId, width, height));
LayerDrawable layerDrawable = new LayerDrawable(layers);
bitmap = BitmapUtils.drawableToBitmap(layerDrawable);
}catch (Exception ex){}
return bitmap;

where BitmapUtils is a custom class that implements bitmap-wise methods.

Using Universal Image Loader library for Android(UIL), this effect is achieved by writing a custom ImageDecoder and applying it to the ImageLoaderConfiguration.

The question is, how can I do this using Glide?


Answer Source

The thing that worked for me:
I used the following answer: http://stackoverflow.com/a/33709650/3106975

public void display(final Context context, String mediaPath, final ImageView imageView, final boolean doApplyOverlay){
                        .into(new SimpleTarget<Bitmap>() {
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                if (doApplyOverlay) {
                                    resource = BitmapUtils.applyOverlay(context, resource, R.drawable.overlay);
        }catch (Exception ex){}

So, to load a bitmap and to interact with it before displaying to the user, you need to implement a custom target and do the interactions there. SimpleTarget class provided by Glide implements the Target interface and allows that kind of things. For more information, you can visit Glide's CustomTargets wiki page on github: https://github.com/bumptech/glide/wiki/Custom-targets