LoginSignup
3
1

More than 5 years have passed since last update.

[Android] リサイズ後のImageのSizeを取得

Last updated at Posted at 2016-08-31

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)とか設定する時に利用していますが皆どうやってるんでしょうか。。
変な所があったり、この様なメソッドが既にあったりしたらご教授願います。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1