为什么当我把图像放在 drawable 文件夹中时 BitmapFactory.decodeResource() 变慢了?

Why is BitmapFactory.decodeResource() slower when I put the images in the drawable folder?

我刚刚在检查一些资源图像的一些解码时间时注意到, 当我将资源图像移动到 drawable 文件夹时,BitmapFactory.decodeResource() 函数大约慢了 3-6 倍。

问题:

有人知道为什么会这样吗?即使图像在 drawable 文件夹中,图像也会缩放吗?是否可以在不在每个文件夹中存储图像副本​​的情况下防止这种情况?

详情:

我使用以下代码只是为了检查图像的解码时间。

for(int i = 0; i < 5; i++){
    long time = System.currentTimeMillis();
    BitmapFactory.decodeResource(getResources(),R.drawable.welcome_01);
    Log.i(TAG, "Time: " + (System.currentTimeMillis() - time));
}

位图大小: 774 x 1280

设备:Nexus 6(如果资源可用,使用 drawable-xxxhdpi 文件夹)

测试结果:

如果图像在 drawable 文件夹中,这些是解码时间:

08-03 09:18:01.072: I/MainActivity(26242): Time: 298
08-03 09:18:01.352: I/MainActivity(26242): Time: 280
08-03 09:18:01.656: I/MainActivity(26242): Time: 304
08-03 09:18:01.929: I/MainActivity(26242): Time: 272
08-03 09:18:02.263: I/MainActivity(26242): Time: 334

如果它们在 drawable-xxxhdpi 文件夹中,结果如下:

08-03 09:19:49.733: I/MainActivity(26456): Time: 54
08-03 09:19:49.786: I/MainActivity(26456): Time: 53
08-03 09:19:49.841: I/MainActivity(26456): Time: 54
08-03 09:19:49.905: I/MainActivity(26456): Time: 64
08-03 09:19:49.966: I/MainActivity(26456): Time: 61

我找到了解决问题的方法。

它可能会对其他人有所帮助。

解法:

将图像放入 drawable-nodpi 文件夹可防止图像被缩放。

附加信息:

在这种情况下,所有其他文件夹中的图像都会缩放, 即使在 drawable 文件夹中。

解码不同文件夹内的资源后,我检查了位图大小。

原始尺寸 774x1280

drawable folder: Bitmap: 2709x4480
drawable-ldpi :  Bitmap: 3612x5973
drawable-mdpi: Bitmap: 2709x4480
drawable-hdpi:  Bitmap: 1806x2987
drawable-xhdpi:  Bitmap: 1355x2240
drawable-xxhdpi: Bitmap: 903x1493
drawable-xxxhdpi: Bitmap: 677x1120
drawable-nodpi:  Bitmap: 774x1280

感谢 Joey Chong I found the official answer to the problem. On the android developers 页面,您可以阅读以下几行:

If resources are not available in the correct density, the system loads the default resources and scales them up or down as needed to match the current screen's density. The system assumes that default resources (those from a directory without configuration qualifiers) are designed for the baseline screen density (mdpi), unless they are loaded from a density-specific resource directory. Pre-scaling is, thus, what the system does when resizing a bitmap to the appropriate size for the current screen density.

简而言之 - 如果您不提供密度,android 将它们作为 mdpi 处理。