androidandroid-glide

How do I make an image perfectly fit its bounds using Glide?


My goal is simple: I want the image to be the exact size of the ImageView, even if that means stretching it to change the aspect ratio. The code I'm using to load the image is fairly simple:

requestManager
    .load(url)
    .placeholder(fallbackDrawable)
    .error(fallbackDrawable)
    .fallback(fallbackDrawable)
    .into(imageView)

By default, this seems to use the fitCenter scale type. If I add android:scaleType="fitXY" to the ImageView in the XML file, this looks correct after the image is loaded, but if the fallback drawable is too big, it's cropped to the top-left rather than shrinking to fit the view's bounds. Calling .override(width, height) doesn't seem to do anything in either case.

What's the best way to achieve this?


Solution

  • I'm not sure if this is the best solution, but if the default looks right for the placeholder and fitXY looks right after the image is loaded, you could install a listener to change the scale type when the image is loaded:

    requestManager
        .load(url)
        .placeholder(fallbackDrawable)
        .error(fallbackDrawable)
        .fallback(fallbackDrawable)
        .listener(object : RequestListener<Drawable?> {
            override fun onLoadFailed(
                e: GlideException?,
                model: Any?,
                target: Target<Drawable?>,
                isFirstResource: Boolean
            ): Boolean {
                return false
            }
    
            override fun onResourceReady(
                resource: Drawable,
                model: Any,
                target: Target<Drawable?>?,
                dataSource: DataSource,
                isFirstResource: Boolean
            ): Boolean {
                imageView.scaleType = ImageView.ScaleType.FIT_XY
                return false
            }
        })
        .into(imageView)