Android在ImageButton中获取图像的尺寸

Android在ImageButton中获取图像的尺寸,android,imagebutton,Android,Imagebutton,是否有方法获取当前在ImageButton中设置的图像尺寸?我正在努力做到这一点 我有一个默认图片为36 x 36的ImageButton。然后我选择一个大小为200 x 200的图像。我想打个电话,比如: imageButton.setImageBitmap(Bitmap.createScaledBitmap( bitmap, 36, 36, true)); 将图像缩小到36 x 36。我希望获得原始图像大小的原因是为了满足hdpi、mdpi和

是否有方法获取当前在
ImageButton
中设置的图像尺寸?我正在努力做到这一点

我有一个默认图片为36 x 36的
ImageButton
。然后我选择一个大小为200 x 200的图像。我想打个电话,比如:

imageButton.setImageBitmap(Bitmap.createScaledBitmap(
                        bitmap, 36, 36, true));
将图像缩小到36 x 36。我希望获得原始图像大小的原因是为了满足hdpi、mdpi和ldpi的要求,以便在将位图添加到
图像按钮之前,我可以将位图的尺寸分别设置为36 x 36、24 x 24和18 x 18。有什么想法吗

哦,老兄,我在随意摆弄代码后得到了答案:

imageButton.getDrawable().getBounds().height();    
imageButton.getDrawable().getBounds().width();
试试这个代码-

imageButton.getDrawable().getBounds().height();    
imageButton.getDrawable().getBounds().width();

Maurice的回答对我来说不太合适,因为我经常会返回0,导致在尝试生成缩放位图时引发异常:

IllegalArgumentException:宽度和高度必须大于0

如果对其他人有帮助的话,我找到了一些其他的选择

选择1
imageButton
是一个
视图
,这意味着我们可以获得
布局参数
,并利用内置的高度和宽度属性。这是我从你的房间里找到的

选择2 让我们的
imageButton
来自扩展
imageButton
的类,然后重写

选择3 获取视图上的绘图矩形,并使用
width()
height()
方法获取尺寸:

android.graphics.Rect r = new android.graphics.Rect();
imageButton.getDrawingRect(r);
int rectW = r.width();
int rectH = r.height();
组合 我的最后一段代码将三者结合起来,并选择了最大值。我这样做是因为我会得到不同的结果,这取决于应用程序所处的阶段(如视图尚未完全绘制时)


你应该把答案贴在下面。
android.graphics.Rect r = new android.graphics.Rect();
imageButton.getDrawingRect(r);
int rectW = r.width();
int rectH = r.height();
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);