Android Get Image Sizes in ImageButton

Is there a way to get the dimensions of the image currently set in ImageButton ? I am trying to achieve this.

I have an ImageButton with a default value of 36 x 36. Then I select a 200 x 200 image. I want to call something like:

 imageButton.setImageBitmap(Bitmap.createScaledBitmap( bitmap, 36, 36, true)); 

to reduce the image to 36 x 36. The reason I want to get the original image size is to maintain hdpi, mdpi and ldpi, so I can set the bitmap sizes to 36 x 36, 24 x 24 and 18 x 18 before Add it to ImageButton . Any ideas?

Oh man, I got the answer after randomly messing with the code:

 imageButton.getDrawable().getBounds().height(); imageButton.getDrawable().getBounds().width(); 
+4
source share
2 answers

Try this code -

 imageButton.getDrawable().getBounds().height(); imageButton.getDrawable().getBounds().width(); 
+4
source

Maurice's answer didn’t quite work for me, since I often get 0 back, which results in an Exception when trying to create a scaled bitmap:

IllegalArgumentException: width and height must be> 0

I found several other options if this helps someone else.

Option 1

imageButton is a View , which means we can get LayoutParams and use the built-in height and width properties. I found this from this other SO answer .

 imageButton.getLayoutParams().width; imageButton.getLayoutParams().height; 

Option 2

Our imageButton has a class that extends imageButton and then overrides the View # onSizeChanged .

Option 3

Get the drawing rectangle in the view and use the width() and height() methods to get the dimensions:

 android.graphics.Rect r = new android.graphics.Rect(); imageButton.getDrawingRect(r); int rectW = r.width(); int rectH = r.height(); 

Combination

My final code completed combining the three and selecting max. I do this because I get different results, depending on what stage the application is at (for example, when the view has not been completely drawn).

 int targetW = imageButton.getDrawable().getBounds().width(); int targetH = imageButton.getDrawable().getBounds().height(); Log.d(TAG, "Calculated the Drawable ImageButton height and width to be: "+targetH+", "+targetW); int layoutW = imageButton.getLayoutParams().width; int layoutH = imageButton.getLayoutParams().height; Log.e(TAG, "Calculated the ImageButton layout height and width to be: "+targetH+", "+targetW); targetW = Math.max(targetW, layoutW); targetH = Math.max(targetW, layoutH); android.graphics.Rect r = new android.graphics.Rect(); imageButton.getDrawingRect(r); int rectW = r.width(); int rectH = r.height(); Log.d(TAG, "Calculated the ImageButton getDrawingRect to be: "+rectW+", "+rectH); targetW = Math.max(targetW, rectW); targetH = Math.max(targetH, rectH); Log.d(TAG, "Requesting a scaled Bitmap of height and width: "+targetH+", "+targetW); Bitmap scaledBmp = Bitmap.createScaledBitmap(bitmap, targetW, targetH, true); 
+1
source

All Articles