【问题标题】:How to get the height and width of ImageView?如何获取ImageView的高度和宽度?
【发布时间】:2014-05-01 17:18:48
【问题描述】:

我正在尝试获取它返回 0 的 ImageView 机器人的高度和宽度

public class FullScreenImage extends FragmentActivity {
    ImageView full_view;
    int width;
    int height;
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);

        setContentView(R.layout.full_screen);

        full_view   = (ImageView)findViewById(R.id.full_view);

        Bundle bundle=getIntent().getExtras();
        byte[] image=   bundle.getByteArray("image");

        width       =     full_view.getWidth();
        height      =     full_view.getHeight();

        Bitmap theImage = BitmapFactory.decodeByteArray(image, 0, image.length);
        Bitmap resized = Bitmap.createScaledBitmap(theImage,width , height, true);

        full_view.setImageBitmap(resized);
    }


}

请帮助我,如何从 ImageView 中找到它?

【问题讨论】:

标签: android android-imageview


【解决方案1】:

新 Android 开发人员常犯的一个错误是在其构造函数中使用视图的宽度和高度。当调用视图的构造函数时,Android 还不知道视图的大小,因此将大小设置为零。实际尺寸是在布局阶段计算的,该阶段发生在施工之后但在绘制任何东西之前。您可以使用onSizeChanged() 方法在值已知时收到通知,也可以稍后使用getWidth()getHeight() 方法,例如在onDraw() 方法中。

【讨论】:

  • 除了 Farhan 已经提到的内容,您还可以查看 http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html
【解决方案2】:

this

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() {
    finalHeight = iv.getMeasuredHeight();
    finalWidth = iv.getMeasuredWidth();
    tv.setText("Height: " + finalHeight + " Width: " + finalWidth);
    return true;
  }
});

【讨论】:

    【解决方案3】:

    如果您第一次获得高度和宽度,则没有可用的图像,因此结果为 0。

    请使用此代码:

     setContentView(R.layout.full_screen);
    
        full_view   = (ImageView)findViewById(R.id.full_view);
    
        Bundle bundle=getIntent().getExtras();
        byte[] image=   bundle.getByteArray("image");
    
    
        Bitmap theImage = BitmapFactory.decodeByteArray(image, 0, image.length);
        Bitmap resized = Bitmap.createScaledBitmap(theImage,width , height, true);
    
        full_view.setImageBitmap(resized);
    
        width       =     full_view.getWidth();
        height      =     full_view.getHeight();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-11
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多