How to get the width and height of an android.widget.ImageView?
╔══════════════════════════════════════════════╗ ^
║ ImageView ╔══════════════╗ ║ |
║ ║ ║ ║ |
║ ║ Actual image ║ ║ |
║ ║ ║ ║ |60px height of ImageView
║ ║ ║ ║ |
║ ║ ║ ║ |
║ ╚══════════════╝ ║ |
╚══════════════════════════════════════════════╝
<------------------------------------------------>
90px width of ImageView
I have an image view with some default height and width, images are stored in db and I want to scale Image according to Imageview height width. As I don't want it give default values because when ever I change it's height and width I also have to change it in code.
I am trying to get the height and width of ImageView but 0 is returned to me in both cases.
int height = ((ImageView) v.findViewById(R.id.img_ItemView)).getHeight();
this returns me 0 even it has default height and width
Solution 1:
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.
Solution 2:
I just set this property and now Android OS is taking care of every thing.
android:adjustViewBounds="true"
Use this in your layout.xml where you have planted your ImageView :D
Solution 3:
I could get image width and height by its drawable;
int width = imgView.getDrawable().getIntrinsicWidth();
int height = imgView.getDrawable().getIntrinsicHeight();
Solution 4:
Post to the UI thread works for me.
final ImageView iv = (ImageView)findViewById(R.id.scaled_image);
iv.post(new Runnable() {
@Override
public void run() {
int width = iv.getMeasuredWidth();
int height = iv.getMeasuredHeight();
}
});