1

I'm trying to get an ImageView to have a specific width (let's say 100dips) but to scale so that the height is whatever value that maintains ratio, so if 4:3 then 75 dips, if 4:5 then 120 dips, etc.

I've tried a few things, but nothing is working. This is my current attempt:

<ImageView
      android:id="@+id/image"
      android:layout_height="wrap_content"
      android:layout_width="100dip"
      android:adjustViewBounds="true"
       android:src="@drawable/stub" 
       android:scaleType="fitCenter" />

The wrap_content for height didn't improve things, it just made the entire image smaller (but did maintain aspect ratio). How can I Accomplish what I'm trying to do?

ajacian81
  • 7,419
  • 9
  • 51
  • 64
  • The proper answer is here: http://stackoverflow.com/questions/4677269/how-to-stretch-three-images-across-the-screen-preserving-aspect-ratio/4688335#4688335. I searched repeatedly but only came across it right as I was posting! :) – ajacian81 Apr 14 '12 at 12:51

1 Answers1

2

Add the follwing class to your project and change your layout like this

View

<my.package.name.AspectRatioImageView
    android:layout_centerHorizontal="true"
    android:src="@drawable/my_image"
    android:id="@+id/my_image"
    android:layout_height="wrap_content"
    android:layout_width="100dp"
    android:adjustViewBounds="true" />

Class

package my.package.name;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * ImageView which scales an image while maintaining
 * the original image aspect ratio
 *
 */
public class AspectRatioImageView extends ImageView {

    /**
     * Constructor
     * 
     * @param Context context
     */
    public AspectRatioImageView(Context context) {

        super(context);
    }

    /**
     * Constructor
     * 
     * @param Context context
     * @param AttributeSet attrs
     */
    public AspectRatioImageView(Context context, AttributeSet attrs) {

        super(context, attrs);
    }

    /**
     * Constructor
     * 
     * @param Context context
     * @param AttributeSet attrs
     * @param int defStyle
     */
    public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) {

        super(context, attrs, defStyle);
    }

    /**
     * Called from the view renderer.
     * Scales the image according to its aspect ratio.
     */
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = width * getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth();
        setMeasuredDimension(width, height);
    }
}
Andreas Linden
  • 12,489
  • 7
  • 51
  • 67