1

私はこのようなイメージビューを持っています

 <ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignTop="@+id/textView3"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="80dp"
    android:layout_marginTop="40dp"
    android:onClick="Time"
    android:adjustViewBounds="false"
    android:src="@drawable/ic_launcher" />

を使用して、画像ビューに表示される画像の幅を取得しようとしています

ImageView artCover = (ImageView)findViewById(R.id.imageView1);
int coverWidth = artCover.getWidth();

ただし、返される幅は画像の幅ではなく画面の幅と同じです(画像の幅が画面の幅よりも小さい場合)。私が行った場合

int coverHeight = artCover.getHeight(); 

画像の正しい高さを取得します。表示された画像の幅を取得するにはどうすればよいですか?

4

3 に答える 3

8

imageviewのビットマップは、おそらくそれに応じてスケーリングおよび整列されます。これを考慮に入れる必要があります。

// Get rectangle of the bitmap (drawable) drawn in the imageView.
RectF bitmapRect = new RectF();
bitmapRect.right = imageView.getDrawable().getIntrinsicWidth();
bitmapRect.bottom = imageView.getDrawable().getIntrinsicHeight();

// Translate and scale the bitmapRect according to the imageview's scale-type, etc. 
Matrix m = imageView.getImageMatrix();
m.mapRect(bitmapRect);

// Get the width of the image as shown on the screen:
int width = bitmapRect.width();

(私は上記のコードをコンパイルしようとはしていませんが、その要点を理解できることに注意してください:-))。上記のコードは、ImageViewがレイアウトを完了した場合にのみ機能します。

于 2013-02-25T15:56:07.607 に答える
1

ビューツリーが完全に測定されるまで待つ必要があります。これは、onPostResume()よりも遅くなる可能性があります。これに対処する1つの方法は次のとおりです。

final ImageView artCover = (ImageView)findViewById(R.id.imageView1);
artCover.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
        public void onGlobalLayout() {
            int coverWidth = artCover.getWidth();
        }
    }
);
于 2013-02-25T14:47:45.050 に答える
1

imageviewから画像を取得でき、画像の幅を取得します。

Bitmap bitmap = ((BitmapDrawable)artCover.getDrawable()).getBitmap();<p>
bitmap.getWidth();
于 2013-02-25T15:04:52.210 に答える