Android中的ImageView控件不支持图片自适应现实,因此我们需要自定义一个ImageView来实现这个功能。下面是实现图片自适应现实的步骤:

  1. 继承ImageView类,重写onMeasure方法。
public class AutoFitImageView extends ImageView {

    public AutoFitImageView(Context context) {
        super(context);
    }

    public AutoFitImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AutoFitImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Drawable d = getDrawable();

        if (d != null) {
            // 图片的实际宽高
            int imageWidth = d.getIntrinsicWidth();
            int imageHeight = d.getIntrinsicHeight();

            // 控件的宽度
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int widthMode = MeasureSpec.getMode(widthMeasureSpec);

            // 控件的高度
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);
            int heightMode = MeasureSpec.getMode(heightMeasureSpec);

            int width, height;

            //计算宽度
            if (widthMode == MeasureSpec.EXACTLY) {
                width = widthSize;
            } else if (widthMode == MeasureSpec.AT_MOST) {
                width = Math.min(imageWidth, widthSize);
            } else {
                width = imageWidth;
            }

            //计算高度
            if (heightMode == MeasureSpec.EXACTLY) {
                height = heightSize;
            } else if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(imageHeight, heightSize);
            } else {
                height = imageHeight;
            }

            setMeasuredDimension(width, height);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}
  1. 在布局文件中使用自定义的ImageView。
<com.example.AutoFitImageView
    android:id="@+id/image_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/image" />

这样,图片就能自适应现实了。当ImageView的宽高设置为match_parent时,图片会根据控件的宽高自适应现实;当ImageView的宽高设置为wrap_content时,图片会根据图片的实际宽高自适应现实


原文地址: https://www.cveoy.top/t/topic/ffhc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录