C# 如何从Xamarin表单中的URI异步加载图像

C# 如何从Xamarin表单中的URI异步加载图像,c#,mobile,asynchronous,xamarin,xamarin.forms,C#,Mobile,Asynchronous,Xamarin,Xamarin.forms,以下是我当前加载图像的代码: System.Uri uri; System.Uri.TryCreate (imageURI, UriKind.Absolute, out uri); _companyImage.Source = ImageSource.FromUri (uri); 问题是整个程序必须等待此任务完成,我想异步加载映像,但无法解决如何异步创建映像源。异步获取数据,并在完成后将其分配给源 System.Uri uri; System.Uri.TryCreate(imageURI, U

以下是我当前加载图像的代码:

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

问题是整个程序必须等待此任务完成,我想异步加载映像,但无法解决如何异步创建映像源。

异步获取数据,并在完成后将其分配给源

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;
System.Uri;
System.Uri.TryCreate(imageURI、UriKind.Absolute、out-Uri);
任务结果=Task.Factory.StartNew(()=>ImageSource.FromUri(uri));
_companyImage.Source=等待结果;

您只需将
Image.Source
属性设置为URI,然后让Xamarin.Forms为您完成工作(per)

例子
将url设置为源属性或从viewmodel绑定


在您试图在Android上使用ContentUri的特殊情况下(例如
content://com.android.contacts/contacts/18/photo
),这是必需的咒语:

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

看,这就是我已经在做的。我是否已经异步加载了映像?或者这有细微的不同?如果您正在执行
ImageSource.FromUri
过程,则很有可能您已经在异步执行该过程(对于本地图像,另一种选择是
ImageSource.FromResource
)。您可以通过将设备置于飞行模式并加载具有URI源图像的任何页面来测试它。需要注意的一点是,这个
FromUri
系统将为您在本地缓存内容。如果您首先通过网络加载,它可能仍然可以处理断开连接的请求。在您发送的文档链接中,它在哪里说它是异步加载的?@jbyrd引用的文档是关于它是如何完成的,而不是文档明确说是异步的。它绝对是异步的;这里没有提到。将第三行替换为
Task result=Task.Factory.StartNew(()=>new-urimagesource{Uri=Uri,CachingEnabled=true,CacheValidity=new-TimeSpan(3,0,0,0)})有什么好处吗@RichardD使用ImageSource.FromUri()与使用新的UriImageSource是一样的。它默认将CachingEnabled设置为true,CacheValidity设置为一天。交换该行只会将缓存时间从一天更改为三天。它说这个表达不受支持
<Image Source="yoururl"  Aspect="AspectFill" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"/>
var uri = Android.Net.Uri.Parse(str);
_companyImage.Source = ImageSource.FromStream(() => Android.App.Application.Context.ContentResolver.OpenInputStream(uri));