ChatGPT解决这个技术问题 Extra ChatGPT

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

«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?
can't you just use android:scaleType="centerInside"?
@nightcracker: That's not ASCII.
@Јοеу When I said "ASCII" I meant "ASCII art", which encompasses more art than that consisting of merely the ASCII character set.
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

C
Community

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.


very nice code brother and logical +1 for that. you can also achieve this by setting ImageView property android:adjustViewBounds="true" to true :)
hey but while debugging pointer don't go minside onPreDraw().Why is it so?
I think you need to add vto.removeOnPreDrawListener(this); line inside onPreDraw()
@KK_07 see the edit as per Sufferer's comment. Just have to remove the listener after you're done with it.
how do you assign values to finalHeight and finalWidth inside an inner class without making them final?
A
AZ_

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


@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.
A
Ankur

I could get image width and height by its drawable;

int width = imgView.getDrawable().getIntrinsicWidth();
int height = imgView.getDrawable().getIntrinsicHeight();

e
element6

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

            }
});

Really helpful!
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 otherwise
P
Pedro Loureiro

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?


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 ?
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.
佚名

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

I
Ian Leslie

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" />

A
Aqib

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

}

onWindowFocusChanged just work on API18 and over, and it can't be best way... however thanks
H
Hiren Patel

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.


c
chikka.anddev

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


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.