Reputation: 125
I have an Image with aspect ratio of (height)3:(width)1 I want this image to fit the width of the screen and keep the aspect ratio.
for example if the screen width is 720 them the width of the image will be 720 and the height of the image will be 720 x 3 (2160)
Upvotes: 1
Views: 332
Reputation: 1725
Solution without ConstraintLayout.
class AspectRatioImageView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
): AppCompatImageView(context, attrs, defStyleAttr) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
var height = (measuredWidth * 3 ).toInt()
setMeasuredDimension(width, height)
}
}
You can then use width as match_parent
and any height
while using AspectRatioImageView
in XML.
Upvotes: 2
Reputation: 125
Hi I managed to solve my problem here is the solution:
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="@drawable/sign1s"
app:layout_constraintDimensionRatio="W,230:350"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
Upvotes: 1