xml 图片占用太多内存 - android

xml images are taking up too much memory - android

嗨,我是 android 的新手,我在使用 xml 定位和设计我的 activity 布局时遇到了一些内存管理问题。 大多数图片都在 100kb 左右,但大小不一,例如图片 1 为 512x512,图片 2 为 120x320 等。 目前,这些图像正在降低我的应用程序的性能,有时甚至会崩溃。 有没有办法减少图像在应用程序中占用的内存量?

您有 3 种解决方案可以执行:

第一个解决方案:

在您的应用程序标签中添加 AppManifest.xml:

android:largeHeap="true"

这将尝试防止您的应用导致 OutOfMemoryError,但请谨慎使用。

Documentation: Whether your application's processes should be created with a large Dalvik heap. This applies to all processes created for the application. It only applies to the first application loaded into a process; if you're using a shared user ID to allow multiple applications to use a process, they all must use this option consistently or they will have unpredictable results. Most apps should not need this and should instead focus on reducing their overall memory usage for improved performance. Enabling this also does not guarantee a fixed increase in available memory, because some devices are constrained by their total available memory.

第二个解:

如果您的图片文件很大,您可以使用此在线工具将它们最小化:http://compresspng.com/

第三个解决方案:

您可以使用 BitmapFactory 加载图像。这是 Android 开发人员文档:http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

应用程序必须经过许多步骤才能理智地处理位图。

  • 小压缩尺寸。平衡磁盘(或在线)格式的质量与文件大小非常重要。能够通过有损预处理器 运行 PNG 文件,或者选择在需要的地方使用 WEBP/JPG 对应用中的每个图像都至关重要。 Smaller PNG Files 涵盖更多内容。但是,这里的问题是这对 内存 大小没有帮助。请记住,当您的图像从磁盘加载时,它们在内存中被解压缩为每像素 32 位(换句话说,没有压缩)。

  • Compressed In Memory Format. Android 提供替代的 565 格式,每个像素仅使用 16 位,而不是 32 位8888格式。如果您正在使用不需要 alpha 的图像,您应该考虑 Smaller Pixel Formats 中讨论的过程以利用将位图加载为 565。

  • 重新使用位图 space。大多数使用缩略图的应用程序一次只能在屏幕上显示 10-20 个缩略图(即使可能有数千个要加载)。 Re-using bitmaps 中描述了这里的技巧。基本上,一旦不再需要缩略图,您可以将其 space 重新用于传入的缩略图,而不是分配一个全新的缩略图。

  • 显示分辨率。加载一个 2MB 的图像是没有意义的,只将它显示为缩略图。相反,您应该将图像缩放到它在设备上显示的分辨率。我讨论了在 .
  • 中加载这些图像的最有效方法

一般来说,像 Picasso and Glide 这样的库在提供使这一切变得更容易的 API 方面做得很好;但他们仍在幕后经历这些相同的过程。