Android - Масштабирование ImageView так, чтобы его ширина всегда составляла 100 единиц.

Я пытаюсь заставить ImageView иметь определенную ширину (скажем, 100 падений), но масштабировать так, чтобы высота была любым значением, поддерживающим соотношение, поэтому, если 4: 3, то 75 падений, если 4: 5, то 120 падений и т. д. .

Я пробовал несколько вещей, но ничего не работает. Это моя текущая попытка:

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

Wrap_content для высоты не улучшил ситуацию, он просто сделал все изображение меньше (но сохранил соотношение сторон). Как я могу выполнить то, что я пытаюсь сделать?


person ajacian81    schedule 14.04.2012    source источник
comment
Правильный ответ здесь: stackoverflow.com/questions/4677269/. Я искал неоднократно, но наткнулся на него только тогда, когда писал! :)   -  person ajacian81    schedule 14.04.2012


Ответы (1)


Добавьте следующий класс в свой проект и измените макет следующим образом.

Просмотреть

<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" />

Класс

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);
    }
}
person Andreas Linden    schedule 14.04.2012