HYH!
HYH!
CC#
Created by HYH! on 7/14/2024 in #help
✅ [Solved] How to fetch some Svg pictures from the web and display them using WinUI 3?
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
LoadSvg("https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/osi.svg");
}

public static async Task<IRandomAccessStream> ConvertStreamReaderToRandomAccessStream(
Stream stream
)
{
// Step 1: Read the content from the StreamReader
StreamReader reader = new StreamReader(stream);
string content = await reader.ReadToEndAsync();

// Step 2: Write the content to a MemoryStream
MemoryStream memoryStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memoryStream);
await writer.WriteAsync(content);
await writer.FlushAsync();
memoryStream.Position = 0;

// Step 3: Convert the MemoryStream to a RandomAccessStream
IRandomAccessStream randomAccessStream = memoryStream.AsRandomAccessStream();

return randomAccessStream;
}

private async void LoadSvg(string url)
{
using (HttpClient client = new HttpClient())
{
var source = new SvgImageSource();
await source.SetSourceAsync(
await ConvertStreamReaderToRandomAccessStream(await client.GetStreamAsync(url))
);
mySvg.Source = source;
}
}
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
LoadSvg("https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/osi.svg");
}

public static async Task<IRandomAccessStream> ConvertStreamReaderToRandomAccessStream(
Stream stream
)
{
// Step 1: Read the content from the StreamReader
StreamReader reader = new StreamReader(stream);
string content = await reader.ReadToEndAsync();

// Step 2: Write the content to a MemoryStream
MemoryStream memoryStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memoryStream);
await writer.WriteAsync(content);
await writer.FlushAsync();
memoryStream.Position = 0;

// Step 3: Convert the MemoryStream to a RandomAccessStream
IRandomAccessStream randomAccessStream = memoryStream.AsRandomAccessStream();

return randomAccessStream;
}

private async void LoadSvg(string url)
{
using (HttpClient client = new HttpClient())
{
var source = new SvgImageSource();
await source.SetSourceAsync(
await ConvertStreamReaderToRandomAccessStream(await client.GetStreamAsync(url))
);
mySvg.Source = source;
}
}
4 replies