在 Android 应用中加载位图比较复杂,原因有很多种:
- 位图很容易就会耗尽应用的内存预算。例如,Pixel 手机上的相机拍摄的照片最大可达 4048x3036 像素(1,200 万像素)。如果使用的位图配置为
ARGB_8888
,这是 Android 2.3(API 级别 9)及更高版本的默认设置,将单张照片加载到内存大约需要 48 MB 内存(4048*3036*4 字节)。如此庞大的内存需求可能会立即耗尽该应用的所有可用内存。 - 在界面线程中加载位图会降低应用的性能,导致响应速度变慢,甚至会导致系统显示 ANR 消息。因此,在使用位图时,必须正确地管理线程处理。
- 如果您的应用将多个位图加载到内存中,您需要娴熟地管理内存和磁盘缓存。否则,应用界面的响应速度和流畅性可能会受到影响。
在大多数情况下,我们建议您使用 Glide 库获取、解码和显示应用中的位图。在处理这些任务以及与位图和 Android 上的其他图片相关的其他任务时,Glide 会将大部分的复杂工作抽象出来。如需了解如何使用和下载 Glide,请访问 GitHub 上的 Glilt 代码库。
您也可以选择直接使用 Android 框架中内置的较低级 API。如需详细了解如何执行此操作,请参阅高效加载较大位图、缓存位图和管理位图内存。
更多资源
How JPG Works
Understand the internals of JPG to get the most out of this file format.
VectorDrawable for smaller APKs (Android Performance Patterns Season 6 Ep. 6)
One of the interesting parts about building an Android application is all the awesome configurations of screen sizes and form factors. And if you’re a developer who prides themselves on being available on the most devices possible, then chances are
How WebP Works (lossly mode)
Learn about WebP, which can give you even smaller image sizes than JPEG.
Reducing JPG File Sizes
Keep your JPGs lean by stripping those unnecessary bits.
Smaller PNGs, and Android's AAPT tool
Use AAPT to help optimize your PNG sizes.
Reducing PNG File Size
Keep your PNGs small and lightweight.
How PNG Works
Understanding how PNGs work can help you use them correctly.
Removing unused resources (Android Performance Patterns Season 4 ep8)
Ok ok, so you’ve watched all the Android Performance Patterns videos, and you know how important it is to be diligent when it comes to bloated APKs. In fact, as soon as a layout file, or bitmap isn’t needed any more by your app, you remove it from