ImageView在任意尺寸下的自适应

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/haoyuegongzi/article/details/78395164

今天研究图片处理的一些功能,发现当图片宽度铺满屏幕宽度的时候,无论怎么设置scaleType属性+adjustViewBounds属性都无法使图片在铺满屏幕宽度的前提下保持宽高比不变,经过参考网上前辈的经验,发现需要自定义IamgeView,重写onMeasure()方法:

具体思路是:获取加载在ImageView中的图片的Drawable对象,然后以屏幕的宽度*Drawable对象的宽高比,获得View的新的高度,然后调用setMeasuredDimension()方法,重新设置宽高参数。具体如下:

public class AdaptiveImageView extends ImageView {
    public AdaptiveImageView(Context context) {//java代码new对象使用
        super(context);
    }

    public AdaptiveImageView(Context context, @Nullable AttributeSet attrs) {
        //xml中布局使用
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Drawable drawable = getDrawable();
        if(drawable == null) {
            return;
        }
        int width = MeasureSpec.getSize(widthMeasureSpec);
        float drawHeight = drawable.getIntrinsicHeight();
        float drawWidth = drawable.getIntrinsicWidth();
        // 控件的宽度width = 屏幕的宽度 MeasureSpec.getSize(widthMeasureSpec);
        // 控件的高度 = 控件的宽度width*图片的宽高比 drawHeight / drawWidth;
        int height = (int) Math.ceil(width * (drawHeight / drawWidth));
        setMeasuredDimension(width, height);
    }
}

xml中这样使用即可:

    <AdaptiveImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@mipmap/shuchang"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"/>

效果图:

自定义之ImageView在任意尺寸下的自适应

猜你喜欢

转载自blog.csdn.net/haoyuegongzi/article/details/78395164