Android Set ImageView Aspect Ratio and Load Image With Glide (Kotlin)

June 18, 2018

NOTE: android-ktx is used in this example.

<ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:scaleType="centerCrop"
    />

The following example will apply 16:9 aspect ratio to ImageView and load the image using Glide.

// make sure we get correct width (after render)
imageView.doOnLayout {
    
    // update height based on 16:9 ratio
    it.updateLayoutParams {
        height = (it.width * 9/16f).toInt()
    }

    // load image when new height are rendered
    it.doOnLayout {

        // glide will follow imageview's width, height and scaleType
        Glide.with(this)
                .load(R.drawable.sample_image)
                .into(imageView)
    }
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.