Last active
December 27, 2022 08:24
-
-
Save AsheeshSharma/9109061c44010cdce2d2bdede660780f to your computer and use it in GitHub Desktop.
Dynamic aspect ratio handling with glide
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun setUpOneDimenNoAspectRatioImage(imageUrl: String?, imageView: AppCompatImageView, @DimenRes defaultHeight: Int, @DimenRes marginToBeAdjusted: Int, availableWidth: Int? = null) { | |
if (imageUrl?.isNotEmpty() == true) { | |
imageView.visibility = View.VISIBLE | |
GlideApp.with(imageView.context) | |
.load(imageUrl) | |
.centerCrop() | |
.into(object : CustomTarget<Drawable>() { | |
override fun onLoadFailed(errorDrawable: Drawable?) { | |
} | |
override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) { | |
val aspectRatio = resource.intrinsicWidth.toFloat() / resource.intrinsicHeight.toFloat() | |
val bitmapWidth = (imageView.context.getDimensionPixelOffset(defaultHeight)) * aspectRatio | |
// if we care about available width there can be a case where | |
// new bitmap width is greater than available width, this code will handle that. | |
if (availableWidth != null && bitmapWidth > availableWidth - imageView.context.getDimensionPixelOffset(marginToBeAdjusted)) { | |
var newWidth = availableWidth - imageView.context.getDimensionPixelOffset(marginToBeAdjusted) | |
var newHeight = newWidth.toFloat() / aspectRatio.toFloat() | |
while (newHeight > (imageView.context.getDimensionPixelOffset(defaultHeight))) { | |
newWidth -= newWidth / 10 | |
newHeight = newWidth.toFloat() / aspectRatio.toFloat() | |
} | |
imageView.layoutParams.apply { | |
width = newWidth | |
height = newHeight.toInt() | |
} | |
} else { | |
imageView.layoutParams.apply { | |
width = bitmapWidth.toInt() | |
height = imageView.context.getDimensionPixelOffset(defaultHeight) | |
} | |
} | |
imageView.setImageDrawable(resource) | |
} | |
override fun onLoadCleared(placeholder: Drawable?) { | |
} | |
}) | |
} else { | |
imageView.visibility = View.GONE | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment