Search code examples
androidbitmapimage-loadingandroid-glideimage-caching

Android Glide: How to download bitmap at specific size?


I'm using Glide to load images on Scale ImageView - it is a custom view with pan and zoom gestures. I should pass Bitmap object to this custom view in order to set picture.

So I can use Glide's .asBitmap() with SimpleTarget:

private SimpleTarget target = new SimpleTarget<Bitmap>() {  
    @Override
    public void onResourceReady(Bitmap bitmap, GlideAnimation glideAnimation) {
       scaleImageView.setImage(ImageSource.bitmap(bitmap));
    }
};

private void loadImageSimpleTarget() {  
    Glide
        .with(context) 
        .load(url)
        .asBitmap()
        .into(target);
}

This code snippet works well, but I will get fullsize Bitmap, which can lead to OutOfMemoryErrors. Also I could specify desired Bitmap size on constructor like this: ...new SimpleTarget<Bitmap>(250, 250)..., but I would have to manually calculate dimensions.

Is there a possibility to pass view (instance of CustomView) to Glide's request, so dimensions will calculated automatically and receive Bitmap object as a result?


Solution

  • Continuing the discussion from the comments, you get 0 for width and height when calling it from onCreateView. However, you can set a listener to be notified when the bounds of the view are actually calculated and then you can get the real width and height by calling getWidth or getHeight:

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
        // ...
        // your other stuff
        // ...
    
        // set listener
        customView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Log.d("debug", "width after = " + customView.getHeight());
    
                // pass the width and height now that it is available
                target = new SimpleTarget<Bitmap>(customView.getWidth(), customView.getHeight()) {  
                    @Override
                    public void onResourceReady(Bitmap bitmap, GlideAnimation glideAnimation) {
                       scaleImageView.setImage(ImageSource.bitmap(bitmap));
                    }
                };
    
                // remove listener, we don't need to be notified again.
                customView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
    }