How to customise imagepath resolving - whistyun/Markdown.Avalonia GitHub Wiki
Relative paths can be used to indicate a hyperlink and a image resource in Markdown.
In Markdown.Avalonia, you can use IPathResolver
to change the way to resolve relative path of image resource.
The following is an example of
- allow only absolute paths to be acquired
- restrict the acquisition of images from the Internet
class MyPathResolver: IPathResolver
{
public string? AssetPathRoot { set; private get; }
public IEnumerable<string>? CallerAssemblyNames { set; private get; }
public async Task<Stream?>? ResolveImageResource(string relativeOrAbsolutePath)
{
if (Uri.TryCreate(relativeOrAbsolutePath, UriKind.Absolute, out var aburl))
{
return await OpenStream(aburl);
}
throw new NotImplementedException();
}
private async Task<Stream?> OpenStream(Uri url)
{
switch (url.Scheme)
{
case "file":
if (!File.Exists(url.LocalPath)) return null;
return File.OpenRead(url.LocalPath);
case "avares":
if (!AssetLoader.Exists(url))
return null;
return AssetLoader.Open(url);
default:
throw new InvalidDataException($"unsupport scheme '{url.Scheme}'");
}
}
}
Set it to the PathResolver property of the MdAvPlugins class to register a PathResolver
<Window
xmlns:md="https://github.com/whistyun/Markdown.Avalonia"
...
>
<Window.Resources>
<local:MyPathResolver x:Key="MyResolver"/>
</Window.Resources>
<md:MarkdownScrollViewer>
<md:MarkdownScrollViewer.Plugins>
<md:MdAvPlugins PathResolver="{StaticResource MyResolver}" />
</md:MarkdownScrollViewer.Plugins>
</md:MarkdownScrollViewer>
</Window>