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

einverne
  • 6,454
  • 6
  • 45
  • 91
AZ_
  • 21,688
  • 25
  • 143
  • 191
  • «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? – Pedro Loureiro Jan 13 '11 at 14:25
  • can't you just use `android:scaleType="centerInside"`? – bigstones Jan 13 '11 at 14:29
  • 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]:http://stackoverflow.com/questions/6590031/how-do-i-find-the-width-height-of-imageview – GregNash Jul 08 '11 at 22:19
  • 2
    @nightcracker: That's not ASCII. – Joey Dec 13 '13 at 14:09
  • 7
    @Јοеу When I said "ASCII" I meant "ASCII art", which encompasses more art than that consisting of merely the ASCII character set. – orlp Dec 13 '13 at 18:19
  • 1
    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 0 – audiojared Jun 07 '19 at 00:08

10 Answers10

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.

Community
  • 1
  • 1
Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274
  • hey but while debugging pointer don't go minside onPreDraw().Why is it so? – Geetanjali Aug 08 '11 at 05:53
  • 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. – mAndroid Sep 22 '11 at 06:23
  • 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? – android developer Apr 11 '13 at 12:16
  • 3
    I think you need to add vto.removeOnPreDrawListener(this); line inside onPreDraw() – sagus_helgy Oct 06 '13 at 08:02
  • @kcoppock i am showing one alert dialog and **onPreDraw** method is calling everytime. Any idea how to avoid that – KK_07k11A0585 May 15 '14 at 12:44
  • 1
    @KK_07 see the edit as per Sufferer's comment. Just have to remove the listener after you're done with it. – Kevin Coppock May 15 '14 at 16:00
  • 8
    how do you assign values to finalHeight and finalWidth inside an inner class without making them final? – Chris Aug 26 '14 at 07:47
  • Cool!! Thank you very much. Do you think you could help me with this question : http://stackoverflow.com/questions/25549679/how-can-i-split-a-long-single-sqliteopenhelper-into-serveral-classes-one-for-e – eddy Aug 28 '14 at 14:03
  • This answer is being [discussed on meta](http://meta.stackoverflow.com/questions/327523/same-answer-by-same-user-posted-in-two-questions?cb=1). – Jean-François Corbett Jul 07 '16 at 12:00
  • The result is really big for me. Is it in dp or other units? – stumped Jul 20 '16 at 18:39
  • @kcoppock : how can we get the exact height of image in imageview ? – Pragya Mendiratta Mar 13 '18 at 05:19
33

I could get image width and height by its drawable;

int width = imgView.getDrawable().getIntrinsicWidth();
int height = imgView.getDrawable().getIntrinsicHeight();
Ankur
  • 1,268
  • 18
  • 22
Rashid
  • 1,515
  • 16
  • 16
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

AZ_
  • 21,688
  • 25
  • 143
  • 191
  • 4
    @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. – AZ_ Sep 09 '14 at 02:37
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();

            }
});
element6
  • 159
  • 1
  • 2
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?

Pedro Loureiro
  • 11,436
  • 2
  • 31
  • 37
  • 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 ? – AZ_ Jan 17 '11 at 13:56
  • 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. – Pedro Loureiro Jan 18 '11 at 00:20
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();
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" />
Ian Leslie
  • 841
  • 1
  • 9
  • 25
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();

}
Aqib
  • 396
  • 4
  • 13
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.

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
-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

chikka.anddev
  • 9,569
  • 7
  • 38
  • 46
  • 2
    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. – AZ_ Jan 13 '11 at 13:41