TheMintRubber
TheMintRubber

Reputation: 113

Bind svg data directly to Image or SvgImageSource

Is there a way to load a svg directly in the Image control, without saving a file that should be loaded as the source of the Image control?

I need to display a svg that I receive from some web api in my UWP application. Currently I save a temp file that I load using the SvgImageSource, like this:

In Xaml:

<Image Name="image"/>

In Code Behind:

var newFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".svg");
var writeStream = await newFile.OpenStreamForWriteAsync();

await writeStream.WriteAsync(Encoding.ASCII.GetBytes(someCustomSvg), 0, someCustomSvg.Length);

writeStream.Dispose();

image.Source = new SvgImageSource(new Uri(newFile.Path));

This works, but is not that efficient.

I would need something that loads the svg into the Image Control without having to save a temp file on the disk.

I know that I can load the svg in a WebView control, but that is also not as efficient as rendering the svg with the Image control.

Is there a way of doing this?

Upvotes: 2

Views: 2475

Answers (1)

Nico Zhu
Nico Zhu

Reputation: 32775

You could use HttpClient to get the stream from web api. And then convert the stream to SvgImageSource. For more detail please refer to the following code.

 private async void MyBtn_Click(object sender, RoutedEventArgs e)
 {
     using (HttpClient client = new HttpClient())
     {
         var svg = new SvgImageSource();
         try
         {
             var response = await client.GetAsync(new Uri("http://www.iconsvg.com/Home/downloadPicture?route=1333158662629220352&name=%E5%9C%86%E5%BD%A2%E7%9A%84_circular164"));

             if (response != null && response.StatusCode == HttpStatusCode.OK)
             {
                 using (var stream = await response.Content.ReadAsStreamAsync())
                 {
                     using (var memStream = new MemoryStream())
                     {
                         await stream.CopyToAsync(memStream);
                         memStream.Position = 0;
                         await svg.SetSourceAsync(memStream.AsRandomAccessStream());
                         MyImageView.Source = svg;
                     }
                 }
             }
         }
         catch (Exception ex)
         {

         }
     }
 }

<Image x:Name="MyImageView" Source="{Binding imageSource ,Mode=OneWay,Converter={StaticResource MyConvert }}" />

I have uploaded code sample to github. Please check.

Upvotes: 1

Related Questions