在Android的项目中我们经常遇见处理图片的时候需要根据图片的大小适配屏幕,特别是在电商项目中商品详情图片这个情况居多。在这种情况下我们就需要重新自定义ImageView来计算图片的尺寸。
比如这种情况下我们需要把图片的宽度定义为充满屏幕,高度就需要自适应,这时候如果我们直接在布局中定义ImageView的宽和高的话图片就会出现拉伸的情况,我们要想解决这个问题就需要自定义ImageView并且在onMeasure()方法中重新计算ImageView的高度
package com.zyb.common.widget;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* 描述:
* 作者:zyb
* 时间:2017年06月03日 18:59
* 版本:2.0
*/
public class AdjustImageView extends android.support.v7.widget.AppCompatImageView {
public AdjustImageView(Context context) {
super(context);
}
public AdjustImageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public AdjustImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable d = getDrawable();
if (d != null) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());
setMeasuredDimension(width, height);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
布局文件如下:
<com.zyb.common.widget.AdjustImageView
android:src="@drawable/img_def2"
android:id="@+id/imageView"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white"/>