Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my code I have an Image View in my XML layout and I keep changing the source image for this in my code. Now I want to know the width and height of the generated image each time.

I tried using getWidth(), getHeight(), getMeasuredWidth(), and getMeasuredHeight(), but they all return 0.

How can I get this?

like image 700
Ankit Avatar asked May 02 '12 10:05

Ankit


3 Answers

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();
}
like image 84
Veer Avatar answered Sep 20 '22 19:09

Veer


try this

 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;
        }
    });
like image 30
Khan Avatar answered Sep 20 '22 19:09

Khan


if you set ImageView a drawable, and the ImageView's height and width type is WRAP_CONTENT, you can get the ImageView's height and width by this even you calling from onCreate()

int height = imageView.getDrawable().getIntrinsicHeight();
int width = imageView.getDrawable().getIntrinsicWidth();
like image 38
canaanhhh Avatar answered Sep 20 '22 19:09

canaanhhh