Search code examples
androidandroid-imageviewandroid-constraintlayout

Android: Keep ratio for a full-width and undefined height ImageView in a ConstraintLayout?


In a ConstraintLayout, an ImageView is bound to its parent in such a way that:

  1. Its left side is bound to the screen's left side

  2. Its right side is bound to the screen's right side

  3. Its top side is bound to a widget's bottom side

  4. Its bottom side is bound to the screen's bottom side

Thus my ImageView appears to be full-width, and its height is the distance between a widget and the bottom of the screen.

<ImageView
    android:id="@+id/imageView16"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:orientation="horizontal"
    android:background="@drawable/ic_background_stars"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@id/linearLayout4"
    app:layout_constraintBottom_toBottomOf="parent"
    />

The problem is that the SVG it contains is also full-width, but the ratio has been destroyed: it's not big enough, in terms of height. So the SVG is distorded.

Question

How could I show the SVG in full-width (from the left screen's side to the right one), keeping its ratio (so that its height would be sufficiently great)?


Solution

  • In addition to the last answer, the reason your image is not being scaled properly is because you are using it as the background.

    Your code..

    android:background="@drawable/ic_background_stars"
    

    Instead, use it as image resource.

    app:srcCompat="@drawable/ic_background_stars"
    

    And the default scale type of ImageView should do the work for you. Else, you can even experiment with various scale types.