Здравствуйте. У меня есть xml-файл с ImageView, в который я загружаю изображение из Интернета (с помощью Picasso), добавляю его в лейаут. Изображения могут и быть разных размеров, следовательно, ImageView должен подгоняться под картинку. Мне нужно, чтобы ширина ImageView была по ширине родителя, а высота подгонялась автоматически. Как это можно правильно реализовать?
1 ответ
Для этих целей использую кастомный 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);
}
}
}
-
Не могли бы вы прокомментировать кодь а то я в первый раз сталкиваюсь с кастомным ImageView – Andrach 3 окт '14 в 4:34
-
@Andrach, копируете этот класс в проект, пишете в xml %имя_пакета%.RatioImageView, и работаете как с обычным ImageView
android:layout_height="wrap_content" android:layout_width="нужная ширина"
и imageView будет сохранять пропорции – katso 3 окт '14 в 4:44