Skip to content

Instantly share code, notes, and snippets.

@kaszabimre
Created September 25, 2023 12:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaszabimre/0b04ccfc3196e3a5c56fb15eb18b88cd to your computer and use it in GitHub Desktop.
Save kaszabimre/0b04ccfc3196e3a5c56fb15eb18b88cd to your computer and use it in GitHub Desktop.
calculateDrawSize() and toIntPx() helper functions
// Function to calculate draw size for the image
private fun ImageBitmap.calculateDrawSize(density: Float, screenWidth: Dp, pagerHeight: Dp): IntSize {
val originalImageWidth = width / density
val originalImageHeight = height / density
val frameAspectRatio = screenWidth / pagerHeight
val imageAspectRatio = originalImageWidth / originalImageHeight
val drawWidth = xOffset + if (frameAspectRatio > imageAspectRatio) {
screenWidth.value
} else {
pagerHeight.value * imageAspectRatio
}
val drawHeight = if (frameAspectRatio > imageAspectRatio) {
screenWidth.value / imageAspectRatio
} else {
pagerHeight.value
}
return IntSize(drawWidth.toIntPx(density), drawHeight.toIntPx(density))
}
// Extension function to convert Float to Int in pixels
private fun Float.toIntPx(density: Float) = (this * density).roundToInt()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment