Android ImageView scale smaller image to width with flexible height without cropping or distortion Android ImageView scale smaller image to width with flexible height without cropping or distortion android android

Android ImageView scale smaller image to width with flexible height without cropping or distortion


I have solved this by creating a java-class that you include in your layout-file:

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

Now, you use this by added your class to your layout-file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent" >    <my.package.name.DynamicImageView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:scaleType="centerCrop"        android:src="@drawable/about_image" /></RelativeLayout>


I had the same problem, as yours. After 30 minutes of trying diffirent variations I solved the problem in this way. It gives you the flexible height, and width adjusted to the parent width

<ImageView            android:id="@+id/imageview_company_logo"            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:adjustViewBounds="true"            android:scaleType="fitCenter"            android:src="@drawable/appicon" />


There is no viable solution within the XML layout standard.

The only reliable way to react to a dynamic image size is to use LayoutParams in code.

Disappointing.