我终于找到了一种解决方案,可以按比例缩放一个图像到设备宽度,而没有内存问题。
首先,您必须以较高的分辨率绘制图像(my_image.png)
仅将此图像放入drawable-xxhdpi文件夹。
使用这个很棒的答案扩展Android ImageView类。
在布局中使用它,如下所示:
这是适合我的布局:
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:fillViewport="true">
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:id="@+id/main_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
android:id="@+id/main_image"
android:adjustViewBounds="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/main_text_view"
android:src="@drawable/my_image"
android:scaleType="fitXY"/>
android:id="@+id/main_image2"
android:adjustViewBounds="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/main_image"
android:src="@drawable/my_image"
android:scaleType="fitXY"/>
android:id="@+id/main_text_view2"
android:layout_below="@id/main_image2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
其他一些最终信息:在找到第3点的解决方案之前,我对第2点(将图像放入哪个文件夹)进行了很多测试。
如果将图像放置在标准drawable文件夹中,则缩放比例在没有第3点的情况下drawable正常工作,但是当android尝试放大已经很大的图像时,Android设备可能会遇到OutOfMemory异常(Android认为drawable图像只是小图像而不检查其大小) 。
当图像位于drawable-xxhdpi文件夹中时,Android会知道其高分辨率,并且仅在必要时进行缩小。 但是,它不能在密度调整装置上将图像缩放到宽度! 例如,在Nexus 10中,图像以其原始大小和比例绘制-不管您为scaleType设置什么(我认为它与inTargetDensity有关,如inScaled描述中所述)。
这里要记住的一件事是我必须在整个内容周围使用ScollView 。 当不涉及ScrollView时,您可能会找到其他解决方案。
最后,您也可以使用drawable-xxxhdpi文件夹,但是它是在API 19中引入的。我尝试过,并且它也适用于较低的API。 显然, Android构建工具19.1.0及更高版本会处理较低的API版本。
我希望这可以帮助别人...