能够在任意尺寸下自适应的ImageView

1. 前言

虽然对于ImageView来说,android:scaleType可以设置显示的图片如何缩放或者移动以适应ImageView的大小。不过,当ImageView的宽度android:layout_width="match_parent"时,我们很难让图片保持宽高比不变,不被拉伸拉长。对于这种情况,我们只能通过自定义ImageView来解决。

2. 解决方案

获取加载在ImageView中的图片的Drawable对象,然后用Drawable对象的宽去乘以宽高比,获得新的高度,然后调用setMeasuredDimension()方法,重新设置宽高参数。相关代码如下:

package com.fantasy.utils.ui;

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

/**
 * 能够在任意尺寸下自适应的ImageView
 * <pre>
 *     author  : Fantasy
 *     version : 1.0, 2018-11-18
 *     since   : 1.0, 2018-11-18
 * </pre>
 */
public class AdaptiveImageView extends AppCompatImageView {
    public AdaptiveImageView(Context context) {//java代码new对象使用
        super(context);
    }

    public AdaptiveImageView(Context context, @Nullable AttributeSet attrs) {
        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();
        int height = (int) Math.ceil(width * (drawHeight / drawWidth));
        setMeasuredDimension(width, height);
    }

}

在xml布局文件中这样使用:

    <com.fantasy.utils.ui.AdaptiveImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_logo" />
发布了43 篇原创文章 · 获赞 34 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/Fantasy_Lin_/article/details/84202624