Search code examples
androidbitmapandroid-imageviewaspect-ratio

Android ImageView - 16:9


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?


Solution

  • EDIT 01/03/2019: After all this time, I strongly recommend using ConstraintLayout that @Eugene Brusov introduced below. I personally would never use my image view that does Math by overriding onMeasure.

    EDIT 03/29/2018: My answer below may be simple, but may be too much of raw answer. If you want to utilize what's already given by Google's ConstraintLayout, follow this answer or scroll down and see @Eugene Brusov's answer.

    Old answer:

    public class CustomImageView extends ImageView {
    
        // some other necessary things
    
        @Override 
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
            int width = getMeasuredWidth();
    
            //force a 16:9 aspect ratio             
            int height = Math.round(width * .5625f);
            setMeasuredDimension(width, height);
        }
    }
    

    Then in your xml

    <path.to.package.CustomImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/img"/>