Android ImageView adjusting parent's height and fitting width Android ImageView adjusting parent's height and fitting width android android

Android ImageView adjusting parent's height and fitting width


Thanks to @Julien and @js. Here is complete solution of ImageView that will stretch bitmap height preserving aspect ratio even if bitmap is smaller than ImageView.

public class ResizableImageView extends ImageView {    public ResizableImageView(Context context, AttributeSet attrs) {        super(context, attrs);    }    @Override     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){         Drawable d = getDrawable();         if(d!=null){                 // ceil not round - avoid thin vertical gaps along the left/right edges                 int width = MeasureSpec.getSize(widthMeasureSpec);                 int height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());                 setMeasuredDimension(width, height);         }else{                 super.onMeasure(widthMeasureSpec, heightMeasureSpec);         }    }}

You can use this class in your xml layouts instead ImageView.

<com.example.ResizableImageView    android:id="@+id/banner"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:src="@drawable/banner" />


You're probably looking for android:adjustViewBounds="true" in xml or imageView.setAdjustViewBounds(true) in Java.


As I mentioned in a comment, I subclassed the ImageView. I found my code, here you go :

    protected class ResizableImageView extends ImageView    {        private Bitmap mBitmap;        // Constructor        public ResizableImageView(Context context)        {            super(context);        }        // Overriden methods          @Override           protected void onMeasure(int widthMeasureSpec,                  int heightMeasureSpec) {              if(mBitmap != null)              {                    int width = MeasureSpec.getSize(widthMeasureSpec);                    int height = width * mBitmap.getHeight() / mBitmap.getWidth();                    setMeasuredDimension(width, height);              }               else              {                  super.onMeasure(widthMeasureSpec,                          heightMeasureSpec);              }              }            @Override            public void setImageBitmap(Bitmap bitmap)            {                mBitmap = bitmap;                 super.setImageBitmap(bitmap);            }    }