How to Get the Width and Height of an Android.Widget.Imageview

How to get the width and height of an android.widget.ImageView?

My answer on this question might help you:

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

You can then add your image scaling work from within the onPreDraw() method.

How to get the width and height of an Image View in android?

Where you calling getWidth() and getHeight() on ImageView? If you calling from onCreate() in activity, it won't work. You need to wait for activity window to attached and then call getWidth() and getHeight() on ImageView. You can try calling getWidth() and getHeight() from onWindowFocusChanged() method of your activity.

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

How to get the height and width of ImageView?

A common mistake made by new Android developers is to use the width and height of a view inside its constructor. When a view’s constructor is called, Android doesn't know yet how big the view will be, so the sizes are set to zero. The real sizes are calculated during the layout stage, which occurs after construction but before anything is drawn. You can use the onSizeChanged() method to be notified of the values when they are known, or you can use the getWidth() and getHeight() methods later, such as in the onDraw() method.

Get ImageView width and height

Quote from "Hello Android (Third Edition)" page 81:

A common mistake made by new Android developers is to use the width and height of a view inside its constructor. When a view’s constructor is called, Android doesn’t know yet how big the view will be, so the sizes are set to zero. The real sizes are calculated during the layout stage, which occurs after construction but before anything is drawn. You can use the onSizeChanged( ) method to be notified of the values when they are known, or you can use the getWidth( ) and getHeight( ) meth- ods later, such as in the onDraw( ) method.



Related Topics



Leave a reply



Submit