如何有效地显示来自 URL 的图像

How to display images from URL efficently

我需要在我的应用程序中显示图像列表,我从 API 调用中获取这些图像作为 URL。现在我正在使用 Glide 来展示它们,但我不喜欢它产生的加载效果(加载时空白 space,以及图像)。有什么方法可以即时显示这些图像,无需任何加载时间,也可能无需下载它们?

您可以通过两种方式显示来自 url 的图像:

  • 没有任何第三方库:

    URL url = new URL("URL of image here");
    Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    imageView.setImageBitmap(bitmap);

由于图像存储在远程服务器上,因此无法绕过下载过程,但是 Glide 确保仅在必要时从远程服务器下载图像,如文档所述

By default, Glide checks multiple layers of caches before starting a new request for an image:

Active resources - Is this image displayed in another View right now? Memory cache - Was this image recently loaded and still in memory? Resource - Has this image been decoded, transformed, and written to the disk cache before? Data - Was the data this image was obtained from written to the disk cache before? The first two steps check to see if the resource is in memory and if so, return the image immediately. The second two steps check to see if the image is on disk and return quickly, but asynchronously.

If all four steps fail to find the image, then Glide will go back to the original source to retrieve the data (the original File, Uri, Url etc).

要解决此问题,

but i don't like the loading effect it makes (blank space while loading, and the the image)

您可以改为在 ImageView 上添加默认占位符,直到下载真实图像。这将在下载实际图像时显示默认图像,然后在下载完成后将其替换为实际图像。

Glide
.with(context)
.load(url)
.placeholder(R.drawable.ic_placeholder) //your default placeholder resource
.into(imageView)