Android ImageView - 16:9

user997777 picture user997777 · Nov 8, 2016 · Viewed 13.3k times · Source

I need to set the Bitmap into ImageView to keep ratio 16:9. Do you have any advice? The main solution is probably in the override method onMeasure of custom ImageView but how?

Answer

Eugene Brusov picture Eugene Brusov · Aug 22, 2017

Since PercentFrameLayout and PercentRelativeLayout were deprecated in API level 26.0.0, I'd suggest you to consider using of ConstraintLayout to keep ratio 16:9 for your ImageView. ConstraintLayout is really powerful tool to build Responsive UI for Android platform, you can find more details here Build a Responsive UI with ConstraintLayout.

Here is the example how to build your ImageView into ConstraintLayout to keep 16:9 ratio:

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginEnd="0dp"
        android:layout_marginStart="0dp"
        android:layout_marginTop="0dp"
        app:srcCompat="@mipmap/ic_launcher"
        app:layout_constraintDimensionRatio="H,16:9"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Don't forget to add constraint-layout dependency to your module's build.gradle file

implementation "com.android.support.constraint:constraint-layout:1.0.2"

Or instead of editing your XML file, edit your layout directly in Layout Editor:

Layout Editor