加载图片后测量ImageView的大小

4
我正在尝试找到一种方法,在使用Glide或Picasso(或任何其他方式)加载图像后,测量ImageView的大小。基本上,我正在尝试以特定位置布局其他视图在图像上方,但需要确定最终ImageView的尺寸才能准确完成此操作。
我不确定尝试执行此操作时使用的最佳布局是什么,但我目前正在使用以下布局:
<FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <ImageView
            android:id="@+id/viewingImageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </FrameLayout>

将图片加载到viewingImageView中。它们都在根FrameLayout中,但我认为这并不重要。

这是我最新的尝试,但是正如注释所述,在ImageView上使用.getWidth().getHeight()返回0。资源的宽度/高度返回原始图像的大小。

Glide

.with(this)
.load(entry.getImageUrl())
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
    @Override
    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
        mImageView.setImageBitmap(resource);

        int width = mImageView.getMaxWidth(); //prints 0
        int height = mImageView.getMaxHeight(); //prints 0
        int resw = resource.getWidth(); //returns original image width
    }
});

那么,如何在图像加载后测量ImageView(或其包装的FrameLayout)?或者如果可能的话,测量最终布局的图像的尺寸会更好,因为我知道根据比例类型,图像并不总是填满整个ImageView。我对任何解决方案都持开放态度,上述只是我迄今为止尝试过的内容。


@Hemanth 也返回0。 - Orbit
你能试一下看这个是否有效吗?mImageView.post(new Runnable() { @Override public void run() { int height = mImageView.getMeasuredHeight(); int width = mImageView.getMeasuredWidth(); } }); 参见这里 - Hemanth
@Hemanth 哈哈,我确实尝试过这个方法,但是我使用了postDelayed并等待了一两秒钟。这确实让我得到了ImageView的最终大小,但这种解决方案有点奇怪,因为我需要尽快叠加项目,而不是等待一个定义好的时间段。 - Orbit
使用 post 方法,您无需等待获取大小。post(Runnable) 会将可运行对象添加到消息队列中。该可运行对象将在 UI 线程上运行。 - Hemanth
mImageView.setImageBitmap(resource); 之后,您是否使用 post 获取宽度和高度? - Hemanth
显示剩余3条评论
2个回答

6

你应该等待视图被绘制,可以像这样使用OnGlobalLayoutListener

ViewTreeObserver vto = mImageView.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
        this.mImageView.getViewTreeObserver().removeGlobalOnLayoutListener(this); 

        // Get the width and height
        int width  = mImageView.getMeasuredWidth();
        int height = mImageView.getMeasuredHeight(); 
    } 
});

我刚刚发现了这个问题。这似乎非常适用于获取imageview的最终尺寸。但是,你有任何想法如何在绘制后获取实际图像的最终尺寸吗? - Orbit
你可能需要获取 ImageView 中 Bitmap 的大小,请查看此链接:https://dev59.com/xFbUa4cB1Zd3GeqPCdqM。 - Marko

1
创建一个带有图片视图的自定义类。 在这个图片视图中使用onMeasure方法,我们可以获取高度和宽度。 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);

if (mNeedsInitialScale) { // Set by setImage when a new image is set
    // The measured width and height were set by super.onMeasure above
    setInitialScale(getMeasuredWidth(), getMeasuredHeight());
    mNeedsInitialScale = false;
}

}


我不太确定如何使用这个。mNeedsInitialScalesetInitialScale 是什么? - Orbit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接