android - 获取 ImageView 中图像的显示大小

标签 android image drawable image-size

代码很简单:

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

请注意 ImageView 使用 fill_parent 作为宽度和高度。

图片 cat 是一个小图片,它会被放大以适应 ImageView,同时保持宽高比。

我的问题是如何获取图片的显示尺寸?我试过:

imageView.getDrawable().getIntrinsicHeight()

但它是图像 cat 的原始高度。

我试过:

imageView.getDrawable().getBounds()

但是返回 Rect(0,0,0,0)

最佳答案

以下将起作用:

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) 现在表示 View 中图像的实际重新缩放(宽度 x 高度)(换句话说,图像的显示大小)


编辑:我认为一种更好的方式来写上面的答案(和一个与整数一起使用的方式):

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

关于android - 获取 ImageView 中图像的显示大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12463155/

相关文章:

android - 如何用我自己的按钮类来固定按钮的宽度

android - SOAP 和 WCF android 之间有什么区别

android - 已发布的 React Native 应用程序从私有(private)存储库中提取更改

android - Visual Studio Code(Flutter) 中的 build.gradle 错误

android - 在 LayerDrawable 中设置 Layer 的可见性

android - 启动画面错误 : android. content.res.Resources$NotFoundException: Drawable

java - 使用数据库进行 Intent 传递的问题

java - 如何在没有绝对路径的java项目中使用图像

html - div 中的图像在图像下方有额外的空间

python - 在我的代码中添加边框和图像