在Xamarin Android中异步从URL加载图像到ImageView

3
我有一个ListView,其中包含多个项,列表中的每个项都应该有一个与之相关联的图像。我已经创建了一个ArrayAdapter来保存每个列表项,并拥有我想要加载的图像的url。
我正在尝试使用Web请求异步加载图像,并在加载完成后设置图像并更新视图,但是视图应立即渲染默认图像。
这是我用来尝试加载图像的方法:
private async Task<Bitmap> GetImageBitmapFromUrl(string url, ImageView imageView)
{
    Bitmap imageBitmap = null;

    try
    {
        var uri = new Uri(url);
        var response = httpClient.GetAsync(uri).Result;

        if (response.IsSuccessStatusCode)
        {
            var imageBytes = await response.Content.ReadAsByteArrayAsync();
            if (imageBytes != null && imageBytes.Length > 0)
            {
                imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
                imageView.SetImageBitmap(imageBitmap);
            }
       }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }

    return imageBitmap;
}

我这样初始化我的 HttpClient:

httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 0, 10);
httpClient.MaxResponseContentBufferSize = 256000;

这里是我调用GetImageFromUrl方法的方式:

ImageView myImage = convertView.FindViewById<ImageView>(Resource.Id.AsyncImageView)
myImage.SetImageBitmap(null);
string url = GetItem(position);
GetImageBitmapFromUrl(url, myImage);

使用这段代码后,请求最终返回了一个错误请求,但是当我查看使用的URL并将其粘贴到浏览器窗口中时,它会显示出我期望的图像。
1个回答

11

您不需要关心下载图像。

在中异步将图像加载到ImageView,有两个好的库可用。

Picasso组件 (源代码) 的使用方法:

Picasso.With(context)
       .Load("http://i.imgur.com/DvpvklR.png")
       .Into(imageView);

FFImageLoading (源代码) 的用法:

ImageService.Instance.LoadUrl(urlToImage).Into(_imageView);

注意(来自文档):

与Picasso不同,您不能将FFImageLoading与标准ImageView一起使用。 相反,只需将图像加载到ImageViewAsync实例中即可。 更新您的代码非常容易,因为ImageViewAsync继承自 ImageView。


1
我选择了Picasso解决方案。谢谢您的快速回复! - Teddy Sterne
1
NuGet 是 Square.Picasso。 - smedasn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接