Android在ImageButton中获取Image的尺寸

时间:2011-07-15 02:33:11

标签: android imagebutton

有没有办法获取ImageButton中当前设置的图像尺寸?我正在努力实现这一目标。

我有ImageButton,默认图片为36 x 36.然后我选择尺寸为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在将其添加到ImageButton之前分别为18。有什么想法吗?

哦,伙计,我随机摆弄了代码后得到了答案:

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

2 个答案:

答案 0 :(得分:5)

试试这段代码 -

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

答案 1 :(得分:2)

莫里斯的回答对我来说并不适合,因为我经常会回来0,导致在尝试生成缩放位图时抛出异常:

  

IllegalArgumentException:width和height必须是> 0

如果它可以帮助其他人,我还找到了其他一些选择。

选项1

imageButtonView,这意味着我们可以获得LayoutParams并利用内置的高度和宽度属性。我是从this other SO answer找到的。

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

选项2

让我们的imageButton来自扩展ImageButton的类,然后覆盖View#onSizeChanged

选项3

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

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

组合

我的最终代码结束了三个并选择了最大值。我这样做是因为我将得到不同的结果,具体取决于应用程序所处的阶段(例如,当View未完全绘制时)。

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);