Square ImageView Maintain Aspect Ratio

May 10, 2018

Utilize ConstraintLayout constraintDimensionRatio. The below configuration constraint height based on width (height follow width size).

<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="wrap_content"
    >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:scaleType="centerCrop"
        app:layout_constraintDimensionRatio="H,1:1"
        />

</android.support.constraint.ConstraintLayout>

Alternatively, you can look into overriding ImageView to create SquareImageView.

public class SquareImageView extends ImageView {    public SquareImageView(Context context) {        super(context);    }    public SquareImageView(Context context, AttributeSet attrs) {        super(context, attrs);    }    public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);        int width = getMeasuredWidth();        setMeasuredDimension(width, width);    }}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.