背景
ImageView 有各种 XML 属性来缩放其内容,以及各种允许放置视图并设置其大小的布局视图。
但是,我无法弄清楚如何在某些情况下很好地缩放 imageView 。
一个例子是将 ImageView 放在底部(例如,frameLayout 的底部),尽可能缩放其宽度,并仍然保持纵横比(不裁剪)。
问题
我发现的所有组合都不起作用,包括各种 ScaleType 值、adjustViewBounds、gravity 等。
看起来 ImageView 错过了一些重要的 ScaleType 值。
我尝试过的
到目前为止,唯一对我有用的解决方案是将 imageView 设置为底部(使用重力设置为底部和中心水平),并使用类似于此的代码:
final ImageView logoBackgroundImageView = ...;
final LayoutParams layoutParams = logoBackgroundImageView.getLayoutParams();
final Options bitmapOptions = ImageService.getBitmapOptions(getResources(), R.drawable.splash_logo);
final int screenWidth = getResources().getDisplayMetrics().widthPixels;
layoutParams.height = bitmapOptions.outHeight * screenWidth / bitmapOptions.outWidth;
logoBackgroundImageView.setLayoutParams(layoutParams);
这通常是有效的,并且不需要太多更改即可使其在非全屏模式下工作,但我想知道是否有更简单的方法。
如果高度太大,它可能不起作用,因此您可能需要更改它,以便在发生这种情况时,将宽度设置得更小,以允许所有内容适合容器。
问题
是否有解决方案或库可以解决与 ImageView 相关的各种问题?
编辑:这是我尝试做的示例图像,这次是在垂直 LinearLayout 中,该 LinearLayout 将 ImageView 限制在中间,位于另外 2 个视图之间:
正如您所看到的,在某些(或全部?)预览中,中间图像向右对齐,而不是保持在中间(水平)。
我希望它占据它所获得的所有空间并进行缩放(保持纵横比),但与它所拥有的空间的底部对齐。
下面是我尝试过的一种组合的 XML 示例:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF339AE2">
<View
android:layout_width="match_parent"
android:id="@+id/topView"
android:layout_alignParentTop="true"
android:layout_height="100dp"
android:background="#FF00ff00"
/>
<FrameLayout
android:layout_below="@+id/topView"
android:layout_width="match_parent"
android:layout_centerHorizontal="true"
android:layout_above="@+id/bottomView"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:background="#FFffff00"
android:layout_gravity="bottom|center_horizontal"
android:src="@android:drawable/sym_def_app_icon"
android:scaleType="fitEnd"
android:layout_height="match_parent"
/>
</FrameLayout>
<View
android:background="#FFff0000"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:id="@+id/bottomView"
android:layout_width="match_parent"
android:layout_height="100dp"/>
</RelativeLayout>
再次请注意,我已经尝试了多种组合,但没有一个起作用,因此如果您建议在 XML 中进行某些更改,请先尝试一下。另请注意,上面是 POC(以便于阅读)。
顺便说一句,我建议的解决方法适用于某些(或大多数?)情况,但并非全部。您只需旋转设备即可注意到它。也许有一种方法可以修复它,或者从 ImageView 扩展以提供额外的情况。