How to get the Dimensions of a Drawable in an ImageView? [duplicate]
Solution 1:
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
.
Solution 2:
Call getIntrinsicHeight and getIntrinsicWidth on the drawable.
public int getIntrinsicHeight ()
Since: API Level 1
Return the intrinsic height of the underlying drawable object. Returns -1 if it has no intrinsic height, such as with a solid color.
public int getIntrinsicWidth ()
Since: API Level 1
Return the intrinsic width of the underlying drawable object.
Returns -1 if it has no intrinsic width, such as with a solid color.
http://developer.android.com/reference/android/graphics/drawable/Drawable.html#getIntrinsicHeight()
This is the size of the original drawable. I think this is what you want.
Solution 3:
The most reliable and powerful way to get drawable dimensions for me has been to use BitmapFactory to decode a Bitmap. It's very flexible - it can decode images from a drawable resource, file, or other different sources.
Here's how to get dimensions from a drawable resource with BitmapFactory:
BitmapFactory.Options o = new BitmapFactory.Options();
o.inTargetDensity = DisplayMetrics.DENSITY_DEFAULT;
Bitmap bmp = BitmapFactory.decodeResource(activity.getResources(),
R.drawable.sample_image, o);
int w = bmp.getWidth();
int h = bmp.getHeight();
Be careful if you use multiple density drawable folders under res, and make sure you specify inTargetDensity on your BitmapFactory.Options to get the drawable of the density you want.
Solution 4:
Efficient way to get Width & Height of Drawable:
Drawable drawable = getResources().getDrawable(R.drawable.ic_home);
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
Log.i("Drawable dimension : W-H", width+"-"+height);
Hope this will help you.
Solution 5:
this solved my problem. It decode the size of image boundary without really load the whole image.
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.img , o);
int w = o.outWidth;
int h = o.outHeight;