Get the displayed size of an image inside an ImageView

后端 未结 4 857
时光取名叫无心
时光取名叫无心 2020-12-01 04:47

The code is simple:



        
4条回答
  •  悲哀的现实
    2020-12-01 05:33

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

提交回复
热议问题