简体   繁体   中英

Get ImageView Width and Height before setting the bitmap

I have an action bar, text view and an imageview in my layout. Imageview has widht and height match_parent. Imageview takes the rest of the space left in the view. I want to set a bitmap to the view but that is too huge. So I first want to get the width and height of the imageview and use them to scale down the bitmap and then set it the imageview. I have tried getting width and height of the imageview in OnCreate, but that is coming as 0,0 probably because imageview has not been created yet.

Please suggest how to do it ?

Thanks.

you need to use the ViewTreeObserver onPreDrawListener, this gets called after everything is measured and right before it is drawn

ImageView iv = (ImageView)findViewBYId(R.id.imageview);
ViewTreeObserver observer = iv.getViewTreeObserver()
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {

    public boolean onPreDraw(){
        observer.removeOnPreDrawListener(this);
        //do your stuff here
    }
}

If you're only interested in layout changes of the particular ImageView, then a layout listener on it might be the way to go:

imageView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        // do stuff
    }
});

Have you tried this link?

http://developer.android.com/training/displaying-bitmaps/load-bitmap.html#load-bitmap

There is basically such a method especially used for preventing memory problems because of large bitmaps. Your first read the dimensions and then laod the scaled sample.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM