Search code examples
androidimagedrawableimage-size

Get the displayed size of an image inside an ImageView


The code is simple:

<ImageView android:layout_width="fill_parent"
           android:layout_height="fill_parent"
           android:src="@drawable/cat"/>

Notice the ImageView used fill_parent for width and height.

The image cat is a small image and it will be zoomed in to fit the ImageView, and keep the width/height ratio at the same time.

My question is how to get the displayed size of the image? I tried:

imageView.getDrawable().getIntrinsicHeight()

But which it the original height of the image cat.

I tried:

imageView.getDrawable().getBounds()

But which returns Rect(0,0,0,0).


Solution

  • the following will work:

    ih=imageView.getMeasuredHeight();//height of imageView
    iw=imageView.getMeasuredWidth();//width of imageView
    iH=imageView.getDrawable().getIntrinsicHeight();//original height of underlying image
    iW=imageView.getDrawable().getIntrinsicWidth();//original width of underlying image
    
    if (ih/iH<=iw/iW) iw=iW*ih/iH;//rescaled width of image within ImageView
    else ih= iH*iw/iW;//rescaled height of image within ImageView
    

    (iw x ih) now represents the actual rescaled (width x height) for the image within the view (in other words the displayed size of the image)


    EDIT: I think a nicer way to write the above answer (and one that works with ints) :

    final int actualHeight, actualWidth;
    final int imageViewHeight = imageView.getHeight(), imageViewWidth = imageView.getWidth();
    final int bitmapHeight = ..., bitmapWidth = ...;
    if (imageViewHeight * bitmapWidth <= imageViewWidth * bitmapHeight) {
        actualWidth = bitmapWidth * imageViewHeight / bitmapHeight;
        actualHeight = imageViewHeight;
    } else {
        actualHeight = bitmapHeight * imageViewWidth / bitmapWidth;
        actualWidth = imageViewWidth;
    }
    
    return new Point(actualWidth,actualHeight);