Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

android - 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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...