Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Dimensions of a Drawable in an ImageView? [duplicate]

What is the best way to retrieve the dimensions of the Drawable in an ImageView?

My ImageView has an Init-Method where I create the ImageView:

private void init() {     coverImg = new ImageView(context);     coverImg.setScaleType(ScaleType.FIT_START);     coverImg.setImageDrawable(getResources().getDrawable(R.drawable.store_blind_cover));     addView(coverImg); } 

At some point during the layout oder measure process I need the exact dimensions of the Drawable to adjust the rest of my Components around it.

coverImg.getHeight() and coverImg.getMeasuredHeight() don't return the results that I need and if I use coverImg.getDrawable().getBounds() I get the dimensions before it was scaled by the ImageView.

Thanks for your help!

like image 969
Philipp Redeker Avatar asked Jan 10 '11 17:01

Philipp Redeker


People also ask

How do I convert to Drawables?

This example demonstrates how do I convert Drawable to a Bitmap in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


1 Answers

Just tried this out and it works for me:

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() {         // Remove after the first run so it doesn't fire forever         iv.getViewTreeObserver().removeOnPreDrawListener(this);         finalHeight = iv.getMeasuredHeight();         finalWidth = iv.getMeasuredWidth();         tv.setText("Height: " + finalHeight + " Width: " + finalWidth);         return true;     } }); 

The ViewTreeObserver will let you monitor the layout just prior to drawing it (i.e. everything has been measured already) and from here you can get the scaled measurements from the ImageView.

like image 108
Kevin Coppock Avatar answered Oct 12 '22 03:10

Kevin Coppock