imageView 中位图的高度和宽度

Height & width of bitmap inside imageView

我使用 imageView 来保存位图,例如,当前位图有 100 x 100 像素。使用以下 xml 文件。

<ImageView
android:id="@+id/pimage"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>

然而,随着 imageView xml 文件的变化,位图的高度和宽度也会发生变化。

<ImageView
android:id="@+id/image"
android:layout_height="400dp"
android:layout_width="match_parent"
android:layout_alignRight="@+id/colorbar"/>

如何找到位图的新高度和宽度?我需要使用高度和宽度作为全局参数,我可以在同一个 class.

中的其他函数中使用它们
final int[] imageWidth = new int[1];
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @SuppressWarnings("deprecation")
    @Override
    public void onGlobalLayout() {
        //get Image Width and height here
        imageWidth[0] = image.getWidth();
        int imageHeight = image.getHeight();
        //Then remove layoutChange Listener
        ViewTreeObserver vto = image.getViewTreeObserver();
        Log.d("Height12", Integer.toString(imageWidth[0]));
        //phaseimage.getViewTreeObserver().removeOnPreDrawListener(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            vto.removeOnGlobalLayoutListener(this);
        } else {
            vto.removeGlobalOnLayoutListener(this);
        }
    }
});
Log.d("Height12", Integer.toString(imageWidth[0]));

函数内部为 728,函数外部为 0。

将位图设置为imageview后,像下面这样使用ViewtreeObserver :

//Your Imageview Reference
ImageView imageView = (ImageView) findViewById(R.id.imageView);

final ViewTreeObserver vto = imageView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
    @SuppressWarnings("deprecation") 
    @Override 
    public void onGlobalLayout() { 
        //get Image Width and height here 
        int imageWidth = imageView.getWidth();
        int imageHeight = imageView.getHeight();

        //Call anyfunction which uses width and height here
        function(imageWidth,imageHeight);

        //Then remove layoutChange Listener 
        ViewTreeObserver vto = imageView.getViewTreeObserver();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            vto.removeOnGlobalLayoutListener(this);
        } else { 
            vto.removeGlobalOnLayoutListener(this);
        } 
    } 
}); 

我终于找到了解决问题的方法。

int imageWidth;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.phase);
    onWindowFocusChanged(hasWindowFocus());
    Log.d("log", Integer.toString(imageWidth))}

@Override
public void onWindowFocusChanged(boolean hasFocus){
    int width=phaseimage.getWidth();
    int height=phaseimage.getHeight();
    imageWidth = width;
    }