经常被问到,从不回答(至少不是以可重复的方式)。
我有一个 ImageView ,其中的图像比 View 小。我想将图像缩放到屏幕的宽度并调整 ImageView 的高度以反射(reflect)图像的比例正确高度。
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
这会导致图像以原始尺寸为中心(小于屏幕宽度),边距位于侧面。不好。
所以我加了
android:adjustViewBounds="true"
同样的效果,不好。我加了
android:scaleType="centerInside"
同样的效果,不好。我将 centerInside
更改为 fitCenter
。一样的效果,不好。我将 centerInside
更改为 centerCrop
。
android:scaleType="centerCrop"
现在,最后,图像缩放到屏幕的宽度 - 但顶部和底部裁剪!所以我把 centerCrop
改成了 fitXY
。
android:scaleType="fitXY"
现在图像被缩放到屏幕的宽度,但没有在 y 轴上缩放,导致图像失真。
删除 android:adjustViewBounds="true"
无效。正如其他地方所建议的那样,添加 android:layout_gravity
再次无效。
我尝试了其他组合 - 无济于事。所以,请问有谁知道:
如何设置 ImageView 的 XML 以填充屏幕宽度、缩放较小的图像以填充整个 View 、以纵横比显示图像而不失真或裁剪?
编辑:我还尝试设置任意数字高度。这仅对 centerCrop
设置有影响。它会根据 View 高度垂直扭曲图像。
最佳答案
我通过创建一个包含在布局文件中的 java 类解决了这个问题:
public class DynamicImageView extends ImageView {
public DynamicImageView(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
final Drawable d = this.getDrawable();
if (d != null) {
// ceil not round - avoid thin vertical gaps along the left/right edges
final int width = MeasureSpec.getSize(widthMeasureSpec);
final int height = (int) Math.ceil(width * (float) d.getIntrinsicHeight() / d.getIntrinsicWidth());
this.setMeasuredDimension(width, height);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
现在,您可以通过将类添加到布局文件中来使用它:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<my.package.name.DynamicImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="@drawable/about_image" />
</RelativeLayout>
关于Android ImageView 将较小的图像缩放到具有灵活高度的宽度,而不会裁剪或扭曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13992535/