ImageViewの実際のサイズを取得したい
Viewを生成する時は何かとViewSizeを取得したい場面が多い。
AndroidではImageViewやImageButtonをscaleTypeで定義することが多いが、リサイズ後のImageSizeを知るメソッドは用意されていない。(多分)
以下のメソッドをUtilityクラスとかで定義しておけば簡単に取得できる。
Utility.java
public static final Point getBitmapSizeFromImageLayer(ImageButton imageLayer) {
final int actualHeight, actualWidth;
final int imageLayerHeight = imageLayer.getHeight(), imageLayerWidth = imageLayer.getWidth();
final int bitmapHeight = imageLayer.getDrawable().getIntrinsicHeight(), bitmapWidth = imageLayer.getDrawable().getIntrinsicWidth();
if (imageLayerHeight * bitmapWidth <= imageLayerWidth * bitmapHeight) {
actualWidth = bitmapWidth * imageLayerHeight / bitmapHeight;
actualHeight = imageLayerHeight;
} else {
actualHeight = bitmapHeight * imageLayerWidth / bitmapWidth;
actualWidth = imageLayerWidth;
}
return new Point(actualWidth, actualHeight);
}
public static final Point getBitmapSizeFromDynamicImageLayer(ImageButton imageLayer) {
final int actualHeight, actualWidth;
final int imageLayerHeight = imageLayer.getLayoutParams().height, imageLayerWidth = imageLayer.getLayoutParams().width;
final int bitmapHeight = imageLayer.getDrawable().getIntrinsicHeight(), bitmapWidth = imageLayer.getDrawable().getIntrinsicWidth();
if (imageLayerHeight * bitmapWidth <= imageLayerWidth * bitmapHeight) {
actualWidth = bitmapWidth * imageLayerHeight / bitmapHeight;
actualHeight = imageLayerHeight;
} else {
actualHeight = bitmapHeight * imageLayerWidth / bitmapWidth;
actualWidth = imageLayerWidth;
}
return new Point(actualWidth, actualHeight);
}
このメソッドはImageButtonオブジェクトを引数で渡すことによってリサイズ後(実際に表示されている)のBitmap画像のサイズをPoint(横幅, 縦幅)
で返してくれる。ImageViewの大きさが欲しい場合も引数部分をImageButton -> ImageView
にするだけで対応できる。
上のメソッドはxml上で定義されているImageButton、
下のメソッドはプログラム上で動的(sizeをlayoutParamsで定義しているオブジェクト)に生成したImageButton
に対応している。
締め
調べても全然出てこなかった。自分はタッチ判定領域(Region)とか設定する時に利用していますが皆どうやってるんでしょうか。。
変な所があったり、この様なメソッドが既にあったりしたらご教授願います。