You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Android中ImageView内图片的实际宽高?

获取ImageView中图片的实际宽高解决方案

嘿,我完全懂你的困扰——你要的是图片本身的真实尺寸,不是ImageView这个容器的宽高对吧?毕竟你的ImageView和父布局都是match_parent,直接拿ImageView的尺寸只会得到屏幕大小。下面给你几个实用的办法,分场景来:

方法一:利用View的post()方法(最简便)

这个方法的核心是让代码在View完成绘制后再执行,这时候图片已经加载到ImageView里了,能直接拿到Drawable的固有尺寸:

yourImageView.post(new Runnable() {
    @Override
    public void run() {
        Drawable drawable = yourImageView.getDrawable();
        if (drawable != null) {
            int actualImgWidth = drawable.getIntrinsicWidth();
            int actualImgHeight = drawable.getIntrinsicHeight();
            // 在这里使用获取到的图片真实宽高就好啦
        }
    }
});

post()里的Runnable会被加入到View的消息队列,等View完成测量、布局、绘制流程后才会执行,完美避开了布局未完成的问题。

方法二:用ViewTreeObserver监听布局完成

如果需要在更早的时机(比如Activity的onCreate阶段)监听图片尺寸,可以用全局布局监听器:

ViewTreeObserver observer = yourImageView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        // 一定要移除监听,防止重复触发
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            yourImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        } else {
            yourImageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
        
        Drawable drawable = yourImageView.getDrawable();
        if (drawable != null) {
            int actualImgWidth = drawable.getIntrinsicWidth();
            int actualImgHeight = drawable.getIntrinsicHeight();
            // 处理尺寸逻辑
        }
    }
});

额外场景:网络加载的图片

如果你的图片是从网络加载的(比如用Glide、Picasso),那得结合图片加载库的回调,等图片完全加载完成后再获取:

以Glide为例:

Glide.with(this)
     .load("你的图片网络地址")
     .listener(new RequestListener<Drawable>() {
         @Override
         public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
             return false; // 让Glide处理错误逻辑
         }

         @Override
         public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
             // 这里的resource就是加载完成的图片,直接拿固有尺寸
             int actualWidth = resource.getIntrinsicWidth();
             int actualHeight = resource.getIntrinsicHeight();
             return false; // 让Glide把图片设置到ImageView里
         }
     })
     .into(yourImageView);

为什么直接拿不行?

在onCreate()或onResume()里直接调用getDrawable().getIntrinsicWidth()大多会返回-1或0,因为这时候ImageView还没完成绘制流程,Drawable还没被正确加载到View中,必须等View的绘制周期完成后才能拿到真实的图片尺寸。

内容的提问来源于stack exchange,提问作者Pragya Mendiratta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:02:58