Asynchronously Load Image from URL into ImageView in Xamarin Android

为君一笑 提交于 2019-12-23 16:34:07

问题


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.

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;
}

I am initializing my HttpClient like so:

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

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);

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.


回答1:


You don't need to care about downloading images.

There exist two good libraries to load an image into a ImageView async in Xamarin.Android.

Picasso component (source) usage:

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

FFImageLoading (source) usage:

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

Note (from documentation):

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.



来源:https://stackoverflow.com/questions/37902950/asynchronously-load-image-from-url-into-imageview-in-xamarin-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!