I’ve got an imageview, like this:
<ImageView
android:id="@+id/add_image_signup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/other_text"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
app:srcCompat="@drawable/add_button" />
which I’m trying to scale programmatically (based on device size) with Layout Params. Something like this works great:
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
val height = displayMetrics.heightPixels
val width = displayMetrics.widthPixels
val addImage = findViewById<ImageView>(R.id.add_image_signup)
val layoutParams = addImage.getLayoutParams()
layoutParams.width = width * 0.3
layoutParams.height = height * 0.1
addImage.setLayoutParams(layoutParams)
and scales the image. However, I’d like to scale only the width, and have the height scale accordingly so that the image maintains its aspect ratio.
I tried only scaling the width, like this:
val addImage = findViewById<ImageView>(R.id.add_image_signup)
val layoutParams = addImage.getLayoutParams()
layoutParams.width = width * 0.3
addImage.setLayoutParams(layoutParams)
but that seems to have no effect.
Is there a way to only specify the width value, and have the height scale accordingly so that the image maintains its aspect ratio?
Thanks
2
Answers
Add fixed width in the XML file and keep the height as wrap_content and see. I don’t think you need to scale it programmatically.
Take the set width and divide it by the aspect ratio to get the height then set it like the code below