【问题标题】:How to load an image asynchronously from URI in Xamarin forms如何从 Xamarin 表单中的 URI 异步加载图像
【发布时间】:2015-07-29 16:15:43
【问题描述】:

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

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

问题是整个程序都要等待这个任务完成,我想异步加载图片但是不知道如何异步创建图片源。

【问题讨论】:

标签: c# mobile asynchronous xamarin xamarin.forms


【解决方案1】:

异步抓取数据并在完成后将其分配给您的源。

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;

【讨论】:

  • 将第三行换成Task&lt;UriImageSource&gt; result = Task&lt;UriImageSource&gt;.Factory.StartNew(() =&gt; new UriImageSource { Uri = uri, CachingEnabled = true, CacheValidity = new TimeSpan(3, 0, 0, 0) });有什么好处
  • @RichardD 使用 ImageSource.FromUri() 与使用新的 UriImageSource 相同。它默认 CachingEnabled 为 true , CacheValidity 为一天。交换那条线只会将缓存时间从一天更改为三天。 developer.xamarin.com/guides/xamarin-forms/working-with/images
  • 表示不支持表达式
【解决方案2】:

您可以简单地将 Image.Source 属性设置为 URI,然后让 Xamarin.Forms 为您完成工作(根据 "Working with Images" in Xamarin.Forms docs)。

示例

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

【讨论】:

  • 这就是我已经在做的事情了。那时我已经异步加载图像了吗?还是这有微妙的不同?
  • 如果您正在执行ImageSource.FromUri 进程,则很有可能您已经在异步执行它(对于本地图像,替代方法是ImageSource.FromResource)。您可以通过将设备置于飞行模式并加载具有您的 URI 来源图像的任何页面来对其进行测试。
  • 需要注意的一点是,这个FromUri 系统会为您在本地缓存内容。如果你先用网络加载它,它可能仍然在断开连接的请求上工作。
  • 您发送的文档链接中的哪个位置说它正在异步加载?
  • @jbyrd 引用的文档是关于它是如何完成的,而不是文档明确地说是异步的。它绝对是异步的;只是那里没有提到。
【解决方案3】:

将您的 url 设置为 Source 属性或从 viewmodel 绑定

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

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

【讨论】:

    【解决方案4】:

    在您尝试在 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));
    

    【讨论】:

      猜你喜欢
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 2022-11-16
      • 1970-01-01
      • 2012-07-19
      • 2017-06-11
      • 1970-01-01
      相关资源
      最近更新 更多