Динамический размер ImageView

Рейтинг: 1Ответов: 1Опубликовано: 03.10.2014

Здравствуйте. У меня есть xml-файл с ImageView, в который я загружаю изображение из Интернета (с помощью Picasso), добавляю его в лейаут. Изображения могут и быть разных размеров, следовательно, ImageView должен подгоняться под картинку. Мне нужно, чтобы ширина ImageView была по ширине родителя, а высота подгонялась автоматически. Как это можно правильно реализовать?

Ответы

▲ 3Принят

Для этих целей использую кастомный ImageView:

public class RatioImageView extends ImageView {
    public RatioImageView(Context context) {
        super(context);
    }

    public RatioImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RatioImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        try {
            Drawable drawable = getDrawable();

            if (drawable == null) {
                setMeasuredDimension(0, 0);
            } else {
                float imageSideRatio = (float) drawable.getIntrinsicWidth() / (float) drawable.getIntrinsicHeight();
                float viewSideRatio = (float) MeasureSpec.getSize(widthMeasureSpec) / (float) MeasureSpec.getSize(heightMeasureSpec);
                if (imageSideRatio >= viewSideRatio) {
                    // Image is wider than the display (ratio)
                    int width = MeasureSpec.getSize(widthMeasureSpec);
                    int height = (int) (width / imageSideRatio);
                    setMeasuredDimension(width, height);
                } else {
                    // Image is taller than the display (ratio)
                    int height = MeasureSpec.getSize(heightMeasureSpec);
                    int width = (int) (height * imageSideRatio);
                    setMeasuredDimension(width, height);
                }
            }
        } catch (Exception e) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}