ImageView自适应高度

有的时候我们的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"/>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值