如何在android中获取图像视图的宽度和高度?

Ank*_*kit 16 android imageview

在我的代码中,我有一个Image ViewXML格式,我在代码中不断更改源代码.现在我想知道每次生成的图像的宽度和高度.

我尝试使用getWidth(),getHeight(), getMeasuredWidth(),和 getMeasuredHeight(),但他们都返回0.

我怎么能得到这个?

Vee*_*eer 43

当你打电话getWidth(),并getHeight()在ImageView的?如果您从onCreate()活动中拨打电话,则无法使用.您需要等待附加活动窗口,然后调用getWidth() and getHeight()ImageView.您可以尝试getWidth() and getHeight()从onWindowFocusChanged()您的活动方法中调用.

@Override
public void onWindowFocusChanged(boolean hasFocus){
    int width=imageView.getWidth();
    int height=imageView.getHeight();
}
Run Code Online (Sandbox Code Playgroud)

  • 如何在片段中执行此操作? (3认同)

Kha*_*han 14

试试这个

 ImageView iv=(ImageView)findViewById(R.id.image);
 ViewTreeObserver vto = iv.getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        public boolean onPreDraw() {
           finalHeight = iv.getMeasuredHeight();
           finalWidth = iv.getMeasuredWidth();
           Log.e("hilength","Height: " + finalHeight + " Width: " + finalWidth);
            return true;
        }
    });
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您将 ImageView 设置为可绘制对象,并且 ImageView 的高度和宽度类型为 WRAP_CONTENT,则即使您从 onCreate()

int height = imageView.getDrawable().getIntrinsicHeight();
int width = imageView.getDrawable().getIntrinsicWidth();
Run Code Online (Sandbox Code Playgroud)