koreus737
koreus737

Reputation: 671

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.

Upvotes: 4

Views: 15053

Answers (4)

Eliot Gillum
Eliot Gillum

Reputation: 912

In the special case that you're trying to use a ContentUri on Android (e.g. content://com.android.contacts/contacts/18/photo), this is the required incantation:

var uri = Android.Net.Uri.Parse(str);
_companyImage.Source = ImageSource.FromStream(() => Android.App.Application.Context.ContentResolver.OpenInputStream(uri));

Upvotes: 0

Swapnil Wakchaure
Swapnil Wakchaure

Reputation: 55

Set your url to Source proprty or bind from viewmodel

https://developer.xamarin.com/guides/xamarin-forms/user-interface/images/

<Image Source="yoururl"  Aspect="AspectFill" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"/>

Upvotes: 0

patridge
patridge

Reputation: 26565

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")),
};

Upvotes: 3

David Hauck
David Hauck

Reputation: 269

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;

Upvotes: 7

Related Questions