a have a problem and need you help! In my application need draw arrow in specific position (for example x = 500, y=500) according original bitmap image( for example width:1230 height:2320) How i can calculate arrow position in my imageView, if i using scaleType="centerCrop" and specific width and height of ImageView? Thanks for help!
class ArrowLayout : RelativeLayout {
lateinit var currentEmotion: EmotionEnums
private var xOffset: Float = 0f
private var yOffset: Float = 0f
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, att: AttributeSet?) : this(context, att, 0)
constructor(context: Context, att: AttributeSet?, def: Int) : super(context, att, def) {
initLayout()
}
private fun initLayout() {
View.inflate(context, R.layout.content_arrow_layout, this)
}
fun showImage(bitmap: Bitmap) {
findViewById<ImageView>(R.id.emotionImage).setImageBitmap(bitmap)
post {
xOffset =
if (bitmap.width >= this.width) -((bitmap.width - this.width) / 2).toFloat()
else ((this.width - bitmap.width) / 2).toFloat()
yOffset =
if (bitmap.height >= this.height) -((bitmap.height - this.height) / 2).toFloat()
else ((this.height - bitmap.height) / 2).toFloat()
drawArrows()
}
}
private fun drawArrows() {
addView(ImageView(context).apply {
layoutParams = LayoutParams(30, 55)
setImageResource(R.drawable.arrow_oblique_right_green)
x = 500 + xOffset
y = 600 + yOffset
requestLayout()
})
}
}
xml of view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/emotionImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
tools:ignore="ContentDescription" />
</RelativeLayout>
Center crop means it will center the image, then crop the outside. So if the image is imgHeight x imgWidth, the view is viewHeight x viewWidth, and the pixel you want to point at is at x,y in the image
if imgHeight > viewHeight, the math is:
Basically reducing the y by the amount of the picture that's cropped off on top (which is half the difference in the heights, the other half is cropped off on the bottom). If this answer is negative or greater than viewHeight, the arrow points offscreen (its cropped out).
if imgHeight <= viewHeight, the math is:
Basically adding the bottom padding to the view height. The bottom padding should be half the difference in heights again.
The x direction works out the same, but with x and widths.