Home » Android » android – Set aspect ratio programmatically for imageView

android – Set aspect ratio programmatically for imageView

Posted by: admin May 14, 2020 Leave a comment

Questions:

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.

How to&Answers:

Late answer, as usual, but this might be useful to someone.

You can set the ratio property programatically by doing the following:

ConstraintSet set = new ConstraintSet();
set.clone(mLayout);
set.setDimensionRatio(mView.getId(), "16:9");
set.applyTo(mLayout);

What I am doing above is getting the layout’s existing ConstraintSet and adding the ratio constraint programmatically before reapplying the ConstraintSet unto the ConstraintLayout (mLayout).

You should get the ConstraintLayout (mLayout) by using the findViewById() method (and manually adding the id property to your ConstraintLayout in your .xml).

Answer:

just changing the layoutParams also works

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