【发布时间】:2020-09-24 15:07:13
【问题描述】:
背景
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 中,它在中间的 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 扩展以提供额外的情况。
【问题讨论】:
-
ImageView.ScaleType.FIT_END 怎么样?
-
@pskink 我试过了。它会将图像缩放到自身的最右端。我试过: android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" android:adjustViewBounds="true" android:scaleType="fitEnd"
-
@pskink 但是,如果我将高度设置为“match_parent”,我不确定我看到了什么。是你的意思吗?
-
然后张贴你得到的图片
-
所以试试这个pastebin.com/CAkuJa9Y
标签: android imageview aspect-ratio