Set aspect ratio programmatically for imageView

Viewed 19955

I have a problem with showing a landscape image without centerCrop. I tried PercentFramelayout, and set aspect ratio programmatically like this:

laParams.percentLayoutInfo.aspectRatio = img.width.toFloat() / img.height.toFloat()

The result is ok -- the application showed all landscape images without centerCrop:

Post loaded successfully

But sometimes I get the wrong aspect ratio:

Wrong aspect ratio 1

Wrong aspect ratio 2

I tried android:adjustViewBounds ="true" but it does not help me. And I used ConstraintLayout, setting the aspect ratio in XML like this:

<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    >

    <android.support.v7.widget.AppCompatImageView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/photo"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="h,16:9"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"

        />
</android.support.constraint.ConstraintLayout>

I got good result, but I load images different size. Images should be without CenterCrop and FitXY. I didn't find any good answers about set aspect ratio programmatically for Constraintlayout I want to show images like instagram or vk.

4 Answers

just changing the layoutParams also works

 (view.layoutParams as ConstraintLayout.LayoutParams).dimensionRatio = "16:9"

you can also check the below code

val layoutParams = imageView.layoutParams as ConstraintLayout.LayoutParams
layoutParams.dimensionRatio = "H,2:1"
imageView.layoutParams = layoutParams

SOLUTION Kotlin 2022:

val parent = ViewGroup(context)
val view   = View(context)

view.apply {
     id           = View.generateViewId()
     layoutParams = ViewGroup.LayoutParams(0, 0)
}

parent.apply {
     id = View.generateViewId()
     removeAllViews()
     addView(rootViewGroup)
}

ConstraintSet().apply {
     clone(parent)

     val viewId   = rootViewGroup.id
     val parentId = parent.id

        connect(viewId, START,  parentId, START)
        connect(viewId, END,    parentId, END)
        connect(viewId, TOP,    parentId, TOP)
        connect(viewId, BOTTOM, parentId, BOTTOM)

        setDimensionRatio(rootId, "1:1")

        applyTo(parent)
}
Related