简体   繁体   English

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

[英]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.问题是整个程序必须等待这个任务完成,我想异步加载图像,但我无法弄清楚如何异步创建图像源。

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;

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 ).您可以简单地将Image.Source属性设置为 URI,并让 Xamarin.Forms 为您完成工作(根据Xamarin.Forms 文档中的“使用图像” )。

Example例子

var someImage = new Image() {
    Aspect = Aspect.AspectFit,
    Source = ImageSource.FromUri(new Uri("http://xamarin.com/content/images/pages/branding/assets/xamagon.png")),
};

Set your url to Source proprty or bind from viewmodel将您的 url 设置为 Source 属性或从视图模型绑定

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

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

In the special case that you're trying to use a ContentUri on Android (eg content://com.android.contacts/contacts/18/photo ), this is the required incantation:在您尝试在 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM