【问题标题】:WinRT preload imagesWinRT 预加载图像
【发布时间】:2014-03-31 20:36:42
【问题描述】:

我有一个 Windows 8.1 XAML 应用程序,我想在页面之间导航之前预加载图像。

我现在的天真代码是:

// Page1.xaml.cs
private void Button_Click(object sender, RoutedEventArgs e)
{
  Frame.Navigate(typeof(Page2));
}

在第二页上:

// Page2.xaml.cs
this.image1.Source = new BitmapImage(new Uri("ms-appx:///Assets/image1.jpg"));
this.image2.Source = new BitmapImage(new Uri("ms-appx:///Assets/image2.jpg"));

现在,当我单击按钮进行导航时,我可以看到正在加载的图像并同时显示一个。我想在按钮单击时预加载图像,并且仅在图像加载后导航。

不幸的是,仅仅创建BitmapImage 对象并等待ImageOpened 事件是行不通的。如果图像未呈现到屏幕上,则似乎未加载图像。

有没有办法强制从代码中加载图像而不将它们添加到可视化树中?

(注意:一种解决方法是以某种不可见的方式将所有图像实际添加到窗口,但如果可能的话,我想避免这种情况)


最终解决方案:

这是我使用SetSourceAsync 提出的,正如 Filip Skakun 所建议的那样:

// Page1.xaml.cs
private async void Button_Click(object sender, RoutedEventArgs e)
{
  bitmapImage1 = new BitmapImage();
  bitmapImage2 = new BitmapImage();

  // Load both images in parallel
  var task1 = loadImageAsync(bitmapImage1, "image1.jpg");
  var task2 = loadImageAsync(bitmapImage2, "image2.jpg");
  await Task.WhenAll(task1, task2);

  Frame.Navigate(typeof(Page2));
}

private Task loadImageAsync(BitmapImage bitmapImage, string path)
{
  var filePath = ApplicationData.Current.LocalFolder.Path + "\\" + path;
  var file = await StorageFile.GetFileFromPathAsync(filePath);
  var stream = await file.OpenAsync(FileAccessMode.Read);
  await bitmapImage.SetSourceAsync(stream);
}
// Page2.xaml.cs
this.image1.Source = bitmapImage1;
this.image2.Source = bitmapImage2;

【问题讨论】:

    标签: c# xaml windows-runtime windows-8.1


    【解决方案1】:

    WinRT XAML 工具包的 AlternativeFrame 控件和 AlternativePage 有一个 ShouldWaitForImagesToLoad 属性,当您设置为 true 并导航到页面时 - 将仅在加载图像时显示页面。 AlternativePage 有一个 Preload() 方法,您也可以覆盖以在显示页面之前添加更多要等待的内容。它的实现方式是首先将页面添加到可视化树中的不可见容器中,因此会触发那些BitmapImages 的加载。

    另一种选择可能是使用您可以等待的SetSourceAsync(),我认为它会在您在 UI 中使用BitmapImage 之前开始加载,但是您需要自己下载文件。

    【讨论】:

    • 我不仅在页面转换中需要这个,在其他地方也需要。所以 AlternativePage 并不是我所需要的。但我确实使用SetSourceAsync 解决了这个问题。谢谢!
    • 我经常做的一件事是使用FrameworkElementExtensions.WaitForImagesToLoad 方法——等待所有Image 源加载到任何可视化树中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 2015-08-12
    • 2018-12-22
    • 1970-01-01
    相关资源
    最近更新 更多