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

10

279
╔══════════════════════════════════════════════╗   ^
║ 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

Ansilme answered 13/1, 2011 at 13:21 Comment(6)
«As I don't want t give default values because when ever I change its height and width I also have to change it in code» - which one can change? the image view or the images stored?Tarragon
can't you just use android:scaleType="centerInside"?Papillary
I was having a similar problem, but I found that the answers posted here didn't help me. I posted my own question, which was answered [here][1]. [1]:#6590531Margenemargent
@nightcracker: That's not ASCII.Ealdorman
@Јοеу When I said "ASCII" I meant "ASCII art", which encompasses more art than that consisting of merely the ASCII character set.Burbank
This doesn't directly answer the question, but if you're wondering why getHeight()/getWidth() are returning 0, they will always return 0 if you call those methods before the view has been "drawn" i.e if you were to call these methods in onCreate() it would return 0Nataline
C
230

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.

Charteris answered 13/1, 2011 at 13:41 Comment(11)
hey but while debugging pointer don't go minside onPreDraw().Why is it so?Tricostate
Hi, this is great but how would I set variables that I can use elsewhere in the activity? If I set instance variables they are not available until onCreate has finished.Eleonoreeleoptene
In case the imageView has a match_parent for its width, and adjustViewBounds set to true, it always returns the full size instead of the one being shown. Is there any other way?Omnivorous
I think you need to add vto.removeOnPreDrawListener(this); line inside onPreDraw()Similar
@kcoppock i am showing one alert dialog and onPreDraw method is calling everytime. Any idea how to avoid thatOatmeal
@KK_07 see the edit as per Sufferer's comment. Just have to remove the listener after you're done with it.Charteris
how do you assign values to finalHeight and finalWidth inside an inner class without making them final?Headquarters
Cool!! Thank you very much. Do you think you could help me with this question : #25550179Spartacus
This answer is being discussed on meta.Gnathion
The result is really big for me. Is it in dp or other units?Glindaglinka
@kcoppock : how can we get the exact height of image in imageview ?Excerpta
E
33

I could get image width and height by its drawable;

int width = imgView.getDrawable().getIntrinsicWidth();
int height = imgView.getDrawable().getIntrinsicHeight();
Exostosis answered 6/8, 2015 at 19:32 Comment(0)
A
32

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

Ansilme answered 13/1, 2011 at 15:13 Comment(1)
@jww I don't really reply to negative voters :p, First read about getWidth and getMeasured in Android documentation. then come and down vote people.Ansilme
D
15

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();

            }
});
Discuss answered 22/2, 2015 at 5:6 Comment(2)
Really helpful!Seasonal
Wrong. Querying width and height from UI doesn't guarantee that those values are ready. The view inflation just happened to be finished in your sample, but it may very well be otherwiseWarty
T
13

The reason the ImageView's dimentions are 0 is because when you are querying them, the view still haven't performed the layout and measure steps. You only told the view how it would "behave" in the layout, but it still didn't calculated where to put each view.

How do you decide the size to give to the image view? Can't you simply use one of the scaling options natively implemented?

Tarragon answered 13/1, 2011 at 14:24 Comment(2)
I have given default height and width to ImageView but when I try to get them in code it returns me 0. I think I have to inflate ImageView first. but how to ?Ansilme
I address that in my answer. Read it again :) I think your view is already inflated. Can you see it? if you can, then it's inflated.Tarragon
F
8

your xml file :

 <ImageView android:id="@+id/imageView"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:src="@drawable/image"
               android:scaleType="fitXY"
               android:adjustViewBounds="true"/>

your java file:

ImageView imageView = (ImageView)findViewById(R.id.imageView);
     int width = imageView.getDrawable().getIntrinsicWidth();
     int   height = imageView.getDrawable().getIntrinsicHeight();
Fiorin answered 13/6, 2017 at 8:51 Comment(0)
G
6

I think you can let the Android OS take care of this for you. Set the scale type on the ImageView to fitXY and the image it displays will be sized to fit the current size of the view.

<ImageView 
    android:layout_width="90px" 
    android:layout_height="60px"
    android:scaleType="fitXY" />
Gantry answered 13/1, 2011 at 13:43 Comment(0)
Y
4

The simplest way is to get the width and height of an ImageView in onWindowFocusChanged method of the activity

 @Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);

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

}
Yeoman answered 26/12, 2014 at 11:11 Comment(1)
onWindowFocusChanged just work on API18 and over, and it can't be best way... however thanksUndesigning
P
1

If you have created multiple images dynamically than try this one:

// initialize your images array

private ImageView myImages[] = new ImageView[your_array_length];

// create programatically and add to parent view

 for (int i = 0; i < your_array_length; i++) {
                myImages[i] = new ImageView(this);
                myImages[i].setId(i + 1);
                myImages[i].setBackgroundResource(your_array[i]);
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                        frontWidth[i], frontHeight[i]);
                ((MarginLayoutParams) params).setMargins(frontX_axis[i],
                        frontY_axis[i], 0, 0);
                myImages[i].setAdjustViewBounds(true);
                myImages[i].setLayoutParams(params);

                if (getIntent() != null && i != your_array,length) {
                    final int j = i;
                    myImages[j].getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                        public boolean onPreDraw() {
                            myImages[j].getViewTreeObserver().removeOnPreDrawListener(this);
                    finalHeight = myImages[j].getMeasuredHeight();
                        finalWidth = myImages[j].getMeasuredWidth();
                    your_textview.setText("Height: " + finalHeight + " Width: " + finalWidth);
                            return true;
                        }
                    });
                }
                your_parent_layout.addView(myImages[i], params);
            }

// That's it. Happy Coding.

Pariah answered 6/11, 2014 at 5:30 Comment(0)
D
-3

my friend by this u are not getting height of image stored in db.but you are getting view height.for getting height of image u have to create bitmap from db,s image.and than u can fetch height and width of imageview

Daphene answered 13/1, 2011 at 13:24 Comment(1)
I know the height and width of image but I want to know the Height and width of ImageView so that I can scale it accordingly. I hope you get my point.Ansilme

© 2022 - 2024 — McMap. All rights reserved.