46

ImageView で Drawable の寸法を取得する最良の方法は何ですか?

ImageViewは私が作成するInit-Methodを持っていますImageView

private void init() {
    coverImg = new ImageView(context);
    coverImg.setScaleType(ScaleType.FIT_START);
    coverImg.setImageDrawable(getResources().getDrawable(R.drawable.store_blind_cover));
    addView(coverImg);
}

レイアウトまたは測定プロセス中のある時点で、ドローアブルの正確な寸法が必要で、ドローアブルの残りのコンポーネントを調整する必要があります。

coverImg.getHeight()coverImg.getMeasuredHeight()私が必要とする結果を返さないでcoverImg.getDrawable().getBounds()くださいImageView.

ご協力いただきありがとうございます!

4

5 に答える 5

53

これを試してみたところ、うまくいきました:

int finalHeight, finalWidth;
final ImageView iv = (ImageView)findViewById(R.id.scaled_image);
final TextView tv = (TextView)findViewById(R.id.size_label);
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    public boolean onPreDraw() {
        // Remove after the first run so it doesn't fire forever
        iv.getViewTreeObserver().removeOnPreDrawListener(this);
        finalHeight = iv.getMeasuredHeight();
        finalWidth = iv.getMeasuredWidth();
        tv.setText("Height: " + finalHeight + " Width: " + finalWidth);
        return true;
    }
});

を使用ViewTreeObserverすると、レイアウトを描画する直前にレイアウトを監視できます (つまり、すべてが既に測定されています)。ここから、 からスケーリングされた測定値を取得できますImageView

于 2011-01-10T17:58:22.593 に答える
46

ドローアブルで getIntrinsicHeight と getIntrinsicWidth を呼び出します。

public int getIntrinsicHeight ()

以来: API レベル 1

基になる描画可能オブジェクトの固有の高さを返します。単色など、固有の高さがない場合は -1 を返します。

public int getIntrinsicWidth ()

以来: API レベル 1

基になる描画可能オブジェクトの固有の幅を返します。

単色など、固有の幅がない場合は -1 を返します。

http://developer.android.com/reference/android/graphics/drawable/Drawable.html#getIntrinsicHeight()

これは元のドローアブルのサイズです。これがあなたの望むものだと思います。

于 2011-01-13T14:28:26.163 に答える
24

私にとって描画可能な寸法を取得する最も信頼性が高く強力な方法は、BitmapFactory を使用して Bitmap をデコードすることでした。非常に柔軟です。ドローアブル リソース、ファイル、またはその他のさまざまなソースから画像をデコードできます。

BitmapFactory を使用してドローアブル リソースから寸法を取得する方法は次のとおりです。

BitmapFactory.Options o = new BitmapFactory.Options();
o.inTargetDensity = DisplayMetrics.DENSITY_DEFAULT;
Bitmap bmp = BitmapFactory.decodeResource(activity.getResources(),
                                               R.drawable.sample_image, o);
int w = bmp.getWidth();
int h = bmp.getHeight();

res の下で複数の密度のドローアブル フォルダーを使用する場合は注意してください。必要な密度のドローアブルを取得するには、BitmapFactory.Options で inTargetDensity を指定してください。

于 2012-01-18T20:52:50.913 に答える
13

Drawableさを取得する効率的な方法:

Drawable drawable = getResources().getDrawable(R.drawable.ic_home);
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
Log.i("Drawable dimension : W-H", width+"-"+height);

これがあなたを助けることを願っています。

于 2016-02-09T12:48:35.020 に答える
6

これは私の問題を解決しました。画像全体を実際にロードすることなく、画像境界のサイズをデコードします。

BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.img , o);
int w = o.outWidth;
int h = o.outHeight;
于 2014-11-24T00:36:03.363 に答える