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!
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With