如何获得在ImageView的一个绘制对象的尺寸?如何获得、尺寸、对象、ImageView

2023-09-12 23:42:22 作者:致命的依赖ゝ

什么是获取绘制对象的尺寸在ImageView的最好的方法是什么?

What is the best way to retrieve the dimensions of the Drawable in an ImageView?

我的ImageView有一个初始化法在那里我创建的ImageView的:

My ImageView has an Init-Method where i create the ImageView:

private void init() {
    coverImg = new ImageView(context);
    coverImg.setScaleType(ScaleType.FIT_START);
    coverImg.setImageDrawable(getResources().getDrawable(R.drawable.store_blind_cover));
    addView(coverImg);
}

目前在布局奥德措施过程中的某个时候,我需要绘制对象的确切尺寸围绕它调整我的组件的其余部分。

At some point during the layout oder measure process i need the exact dimensions of the Drawable to adjust the rest of my Components around it.

coverImg.getHeight() coverImg.getMeasuredHeight()不回,我需要的结果和如果我使用 coverImg.getDrawable()的getBounds()我得到的尺寸有人比例由ImageView的面前。

coverImg.getHeight() and coverImg.getMeasuredHeight() don't return the results that i need and if i use coverImg.getDrawable().getBounds() i get the dimensions before it was scaled by the ImageView.

感谢您的帮助!

推荐答案

只是尝试这样做了,它为我的作品:

Just tried this out and it works for me:

int finalHeight, finalWidth;
final ImageView iv = (ImageView)findViewById(R.id.scaled_image);
final TextView tv = (TextView)findViewById(R.id.size_label);
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    public boolean onPreDraw() {
        // Remove after the first run so it doesn't fire forever
        iv.getViewTreeObserver().removeOnPreDrawListener(this);
        finalHeight = iv.getMeasuredHeight();
        finalWidth = iv.getMeasuredWidth();
        tv.setText("Height: " + finalHeight + " Width: " + finalWidth);
        return true;
    }
});

ViewTreeObserver 将让你监控的布局图纸只是之前(即一切都已经被测量),从这里您可以从的ImageView 。

The ViewTreeObserver will let you monitor the layout just prior to drawing it (i.e. everything has been measured already) and from here you can get the scaled measurements from the ImageView.