C
C#5mo ago
HYH!

✅ [Solved] How to fetch some Svg pictures from the web and display them using WinUI 3?

I have some experience in front-end web development, but I found it so difficult to solve this problem that I almost didn't want to touch WinUI anymore.
2 Replies
HYH!
HYH!OP5mo ago
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;
}
}
MODiX
MODiX5mo ago
If you have no further questions, please use /close to mark the forum thread as answered If you have no further questions, please use /close to mark the forum thread as answered
Want results from more Discord servers?
Add your server