异步将图像从URL加载到Xamarin Android中的ImageView中
我有一个包含多个项目的ListView,列表中的每个项目都应该有一个与之关联的图像。我创建了一个数组适配器来保存每个列表项并拥有我想要加载的图像的URL。
I have a ListView of multiple items and each item in the list should have an image associated with it. I have created an Array Adapter to hold each list item and have the url of the image I wish to load.
我试图使用Web请求异步加载图像并设置图像并在视图加载后在视图中更新它,但视图应立即使用默认图像渲染。
I am trying to asynchronously load the image using a web request and have it set the image and update it in the view once it has been loaded but the view should render immediatly with a default image.
这是我正在使用的方法尝试加载图像
Here is the method I am using to try to load the image
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,如下所示:
I am initializing my HttpClient like so:
httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 0, 10);
httpClient.MaxResponseContentBufferSize = 256000;
以下是我调用GetImageFromUrl方法的方法
And here is how I am calling the GetImageFromUrl Method
ImageView myImage = convertView.FindViewById<ImageView>(Resource.Id.AsyncImageView)
myImage.SetImageBitmap(null);
string url = GetItem(position);
GetImageBitmapFromUrl(url, myImage);
使用此代码时,请求最终会返回错误的请求但是当我查看我正在使用的URL时并将其粘贴到浏览器窗口中,它会显示我期待的图像。
Using this code the request eventually comes back with a bad request but when I view the url I am using and paste it into a browser window it brings up the image I am expecting.
您无需关心下载图片。
在中有两个好的库可以将图像加载到
。 ImageView
async中Xamarin.Android
There exist two good libraries to load an image into a ImageView
async in Xamarin.Android
.
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,因此更新代码非常简单。
Unlike Picasso you cannot use FFImageLoading with standard ImageViews. Instead simply load your images into ImageViewAsync instances. Updating your code is very easy since ImageViewAsync inherits from ImageView.