如何获得ImageView的高度和宽度?

时间:2014-03-24 11:18:38

标签: android android-imageview

我正在努力获得身高和高度ImageView bot的宽度为0

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中找到它?

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

请参阅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;
  }
});

答案 2 :(得分:0)

如果您第一次获得高度和宽度,那么没有可用的图像,因此结果为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();