Reputation: 133
I have an imageview that looks like this
<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" />
I'm trying to get the width of the image displayed in the imageview by using
ImageView artCover = (ImageView)findViewById(R.id.imageView1);
int coverWidth = artCover.getWidth();
But the width returned is the same as the screen width and not of the image (when the image width is less then the screen width). If I do
int coverHeight = artCover.getHeight();
I get the correct height of the image. How can I get the width of the displayed image?
Upvotes: 1
Views: 2623
Reputation: 4981
You can get image from imageview and will get width the image.
Bitmap bitmap = ((BitmapDrawable)artCover.getDrawable()).getBitmap();<p>
bitmap.getWidth();
Upvotes: 1
Reputation: 12596
Your imageview's bitmap is probably scaled and aligned accordingly. You need to take this into account.
// 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();
(note that I haven't tried to compile above code, but you'll get the gist of it :-)). The above code only works when the ImageView has completed its layout.
Upvotes: 8
Reputation: 28856
You have to wait till the View tree has been measured completely which might be even later than onPostResume(). One way to deal with that is:
final ImageView artCover = (ImageView)findViewById(R.id.imageView1);
artCover.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int coverWidth = artCover.getWidth();
}
}
);
Upvotes: 1