Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load an image asynchronously from URI in Xamarin forms

Here is my current code for loading the Image:

System.Uri uri;
System.Uri.TryCreate (imageURI, UriKind.Absolute, out uri);
_companyImage.Source = ImageSource.FromUri (uri);

The problem is that the whole program has to wait for this task to complete, I would like to load the image asynchronously but I can't work out how to create an image source asynchronously.

like image 239
koreus737 Avatar asked Dec 24 '22 16:12

koreus737


2 Answers

Grab the data asynchronously and assign it to your Source once it is done.

System.Uri uri;
System.Uri.TryCreate(imageURI, UriKind.Absolute, out uri);
Task<ImageSource> result = Task<ImageSource>.Factory.StartNew(() => ImageSource.FromUri(uri));
_companyImage.Source = await result;
like image 185
David Hauck Avatar answered Dec 29 '22 07:12

David Hauck


You can simply set the Image.Source property to a URI and let Xamarin.Forms do the work for you (per "Working with Images" in Xamarin.Forms docs).

Example

var someImage = new Image() {
    Aspect = Aspect.AspectFit,
    Source = ImageSource.FromUri(new Uri("http://xamarin.com/content/images/pages/branding/assets/xamagon.png")),
};
like image 42
patridge Avatar answered Dec 29 '22 07:12

patridge