2017-04-13 93 views
0

在這種link顯示資源地圖圖像

它向我們展示瞭如何使用這兩個文本,並通過使用ResourceMap的圖像的內容分享出來的HTML。

但是相應的article沒有向我們展示如何正確讀取它並將其放入webview中。

我知道如何獲取資源地圖,但我不知道如何最好地將它放入WebView

this.sharedResourceMap = await this.shareOperation.Data.GetResourceMapAsync(); 
foreach (KeyValuePair<string, RandomAccessStreamReference> item in this.sharedResourceMap) 
{ 
    ResourceMapValue.Text += "\nKey: " + item.Key; 
} 

Item.Key將會像ms-appx:///Assets/Logo.png

+0

https://stackoverflow.com/questions/41401047/display-local-images-in-uwp-webview-control/41423396#41423396是一個相關的問題,但他們必須在本地文件夾,其中的文件我的是在這個「資產」文件夾 – freshWoWer

回答

1

你應該充分利用類IUriToStreamResolver

在下面的示例中,我加載位於Assets文件夾中的HTML文件(example.html)。 Assets文件夾還包含HTML文件的所有圖像。 應該覆蓋GetContent方法IUriToStreamResolver以將任何請求轉換爲HTML文件中指定的URI(如)轉換爲本地URI路徑。在你的情況下,你可能需要調整GetContent以檢索你的資源地圖存儲的文件。

public sealed partial class WebViewLocalImage : Page 
{ 
    public WebViewLocalImage() 
    { 
     this.InitializeComponent(); 
     Loaded += MainPage_Loaded; 
    } 

    private void MainPage_Loaded(object sender, RoutedEventArgs e) 
    { 
     var uri = this.myWebView.BuildLocalStreamUri("InternalAssets", "example.html"); 
     this.myWebView.NavigateToLocalStreamUri(uri, new StreamUriResolver()); 
    } 
} 

public sealed class StreamUriResolver : IUriToStreamResolver 
{ 
    public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri) 
    { 
     string path = uri.AbsolutePath; 
     return GetContent(path).AsAsyncOperation(); 
    } 

    private async Task<IInputStream> GetContent(string URIPath) 
    { 
     try 
     { 
      Uri localUri = new Uri("ms-appx:///Assets/" + URIPath); 
      StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(localUri); 
      IRandomAccessStream stream = await f.OpenAsync(FileAccessMode.Read); 
      return stream.GetInputStreamAt(0); 
     } 
     catch (Exception) 
     { 
      System.Diagnostics.Debug.WriteLine("Invalid URI"); 
     } 
     return null; 
    } 
} 
+0

謝謝!你的答案讓我研究IUriToStreamResolver的更多信息。順便說一句,我正在寫一個共享目標,GetHtmlFormatAsync會從共享源返回一個字符串。由於NavigateToString沒有能力讀取本地圖像。這是否意味着我必須首先將從GetHtmlFormatAsync收到的HTML片段寫入文件example.html,然後繼續使用BuildLocalStreamUri和NavigateToLocalStreamUri? – freshWoWer

+0

然後我們必須手動刪除它? – freshWoWer

+0

我已通過使用'ms-appx-web'協議成功讀取本地圖像。嘗試以下代碼:'string htmlContent =「

這裏是一個本地圖像:

」; myWebView.NavigateToString(htmlContent);' –