Mxwan
Mxwan

Reputation: 191

Use ratio for ImageView size with ConstrainLayout for Responsiveness

I'm using ConstraintLayout to make my app responsive to different screen size.

I want to use ratio to size my widgets. So to use ratio I have to set my width and height to match_constraints.

So what I'm doing is :

    <ImageView
    android:id="@+id/my_img"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginBottom="150dp"
    android:layout_marginStart="250dp"
    android:layout_marginTop="5dp"
    android:adjustViewBounds="true"
    android:src="@drawable/img_test"
    app:layout_constraintBottom_toTopOf="@+id/bot_img"
    app:layout_constraintDimensionRatio="h,125:50"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/top_img" />

So I will use margins and ratios,in dp, to set up my img size. The problem is that when I'm using different screen size, my img will not keep the exact ratio I want.

Can you help me ? Am I using ConstraintLayout right ? Thanks a lot

Upvotes: 4

Views: 1133

Answers (1)

Piyush Kumar
Piyush Kumar

Reputation: 631

I think you misunderstood the use of constraintDimensionRatio. Set your both horizontal constraints with width="0dp" as well as set constraintDimensionRatio (like 1:1). And set only one vertical constraint (like top) with height="0dp" and leave the other one (or vice-versa depending on your requirement). Now your view's width will expand as much as it can and height will adjust to the ratio. See below example for better understanding.

<ImageView
    android:id="@+id/my_img"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:scaleType="centerCrop"
    android:src="@drawable/img_test"
    app:layout_constraintDimensionRatio="1:1"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"/>

Above code will result into a square image which will scale itself for different parent widths.

Happy codding :)

Upvotes: 4

Related Questions