Use CustomTarget from Glide to pass the dimensions of your image view so that Glide can scale down the images to the specified size.
Glide.with(this)
.load(IMAGE_URL)
.into(object : CustomTarget<Drawable>(targetImageWidth, targetImageHeight) {
override fun onLoadCleared(placeholder: Drawable?) {
// called when imageView is cleared. If you are referencing the bitmap
// somewhere else too other than this imageView clear it here
}
override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
image.setImageDrawable(resource)
}
})
But what if you only know one dimension of the target container and don’t know the aspect ratio of the image? Are you forced to use the original image size? It turns out there may be a way to work around this. In this case, just set the other dimension which you do not know to 1, and Glide will automatically scale down your image.
imageView.viewTreeObserver.addOnGlobalLayoutListener {
Glide.with(this)
.load(TargetActivity.IMAGE_URL)
.into(object : CustomTarget<Drawable>(imageView.width, 1) {
// imageView width is 1080, height is set to wrap_content
override fun onLoadCleared(placeholder: Drawable?) {
// clear resources
}
override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
// bitmap will have size 1080 x 805 (original: 1571 x 1171)
imageView.setImageDrawable(resource)
}
})
}