简体   繁体   中英

Display resource map image in UWP WebView Control

In this link

It shows us how to share out HTML with content of both text and an image through use of ResourceMap.

But the corresponding article is not showing us how to read it and put it in the webview properly.

I know how to get the resource map back, but I don't know how best to put it into the WebView .

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

Item.Key will be something like ms-appx:///Assets/Logo.png

You should leverage the class IUriToStreamResolver .

In the following example, I load the HTML file (example.html) located in Assets folder. The Assets folder also contains all images of the HTML file. The GetContent method of IUriToStreamResolver should be overriden to transform any request to an URI specified in the HTML file (such as ) into a local uri path. In your case, you may have to tweak the GetContent so as to retrieves file stored by your resource map.

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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