您的位置:首页 > 移动开发 > Android开发

ImageView自适应高度

2017-06-06 09:19 211 查看
有的时候我们的ImageView设置图片的时候需要指定宽度,然后自适应高度,比如商城中的商品详情图片:





这种样式的宽度是手机的瓶宽,高度根据宽度自适应。为了实现这种效果可以自定义ImageView,在onMeasure中重新计算ImageView的高度:

package com.lianjiu.b.common.widget;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
* 描述:
* 作者:Linxz
* E-mail:lin_xiao_zhang@163.com
* 时间: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);

}
}
}


布局xml中处理如下:

<com.lianjiu.b.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"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  imageview android