this is my way to get the actual coordinates of the image displayed in the image view.
Create a class with this code of mine
class GetIntrinsicImageview(
private val context: Context) {
data class Coordinator(
val top: Float,
val left: Float,
val right: Float,
val bottom: Float
)
fun getCoordinator(iv: ImageView, bitmap: Bitmap): Coordinator {
val drawable = iv.drawable
val imageIntrinsicWidth = drawable.intrinsicWidth
val imageIntrinsicHeight = drawable.intrinsicHeight
val imageViewAspectRatio = iv.width.toFloat() / iv.height.toFloat()
val bitmapAspectRatio = bitmap.width.toFloat() / bitmap.height.toFloat()
val imageViewRect = Rect()
iv.getGlobalVisibleRect(imageViewRect)
val widthImageView = iv.width
val heightImageView = iv.height
val imageViewLeft = imageViewRect.left
val imageViewTop = imageViewRect.top
val imageViewRight = imageViewRect.right
val imageViewBottom = imageViewRect.bottom
var topBitmap = 0f
var bottomBitmap = 0f
var leftBitmap = 0f
var rightBitmap = 0f
if (imageViewAspectRatio > bitmapAspectRatio) {
val heightBitmap = heightImageView
val widthBitmap =
(heightBitmap.toFloat() / imageIntrinsicHeight.toFloat()) * imageIntrinsicWidth
val y = (widthImageView.toFloat() - widthBitmap.toFloat()) / 2
topBitmap = imageViewTop.toFloat()
bottomBitmap = imageViewBottom.toFloat()
leftBitmap = imageViewLeft + y
rightBitmap = leftBitmap + widthBitmap
} else {
val widthBitmap = widthImageView
val heightBitmap =
(widthBitmap.toFloat() / imageIntrinsicWidth.toFloat()) * imageIntrinsicHeight
val x = (heightImageView.toFloat() - heightBitmap.toFloat()) / 2
topBitmap = imageViewTop + x
bottomBitmap = topBitmap + heightBitmap
rightBitmap = imageViewRight.toFloat()
leftBitmap = imageViewLeft.toFloat()
}
val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
var statusBarHeight =
if (resourceId > 0) context.resources.getDimensionPixelSize(resourceId) else 0
topBitmap -= statusBarHeight
bottomBitmap -= statusBarHeight
return Coordinator(topBitmap, leftBitmap, rightBitmap, bottomBitmap)
}
}
To use it in activity or fragment, or anywhere
binding.btLog.setOnClickListener {
val intrinsic = GetIntrinsicImageview(this)
val coordinator = intrinsic.getCoordinator(binding.iv, mBitmap)
val left = coordinator.left
val top = coordinator.top
val right = coordinator.right
val bottom = coordinator.bottom
}
you need to enter that bitmap and imageview, the returned result will be top, bottom, right and left