代码很简单:
<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/