Maurice's answer didn't quite work for me, as I would frequently get 0 back, resulting in an Exception being thrown whenever trying to generate the scaled bitmap:
IllegalArgumentException: width and height must be > 0
I found a few other options if it helps anyone else.
Option 1
The imageButton
is a View
which means we can get the LayoutParams
and take advantage of the built-in height and width properties. I found this from this other SO answer.
imageButton.getLayoutParams().width;
imageButton.getLayoutParams().height;
Option 2
Have our imageButton
come from a Class which extends ImageButton
, and then override View#onSizeChanged.
Option 3
Get the drawing rectangle on 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 ended up combining the three and selecting the max. I am doing this because I will get different results, depending on which phase the application is in (like when the View has not been fully drawn).
int targetW = imageButton.getDrawable().getBounds().width();
int targetH = imageButton.getDrawable().getBounds().height();
Log.d(TAG, "Calculated the Drawable ImageButton's height and width to be: "+targetH+", "+targetW);
int layoutW = imageButton.getLayoutParams().width;
int layoutH = imageButton.getLayoutParams().height;
Log.e(TAG, "Calculated the ImageButton's 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's 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);