Created
August 5, 2023 05:39
-
-
Save emoacht/075d3bbde01a299617f038797c1c4324 to your computer and use it in GitHub Desktop.
Helper method for Windows.UI.Xaml.Media.Imaging.SvgImageSource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.IO; | |
using System.Text; | |
using System.Text.RegularExpressions; | |
using System.Threading.Tasks; | |
using System.Xml.Linq; | |
using Windows.Storage; | |
using Windows.Storage.Streams; | |
using Windows.UI.Xaml.Media.Imaging; | |
public static class SvgImageHelper | |
{ | |
public static async Task<SvgImageSource> GetImageAsync(StorageFile file) | |
{ | |
using IRandomAccessStream fs = await file.OpenAsync(FileAccessMode.Read); | |
using StreamReader sr = new StreamReader(fs.AsStreamForRead(), Encoding.UTF8); | |
string svgString = await sr.ReadToEndAsync(); | |
XDocument doc = XDocument.Parse(svgString); | |
double originalWidth = GetValue(doc.Root.Attribute("width")?.Value); | |
double originalHeight = GetValue(doc.Root.Attribute("height")?.Value); | |
if (originalWidth == 0 || originalHeight == 0) | |
return null; | |
fs.Seek(0); | |
Debug.WriteLine($"width:{originalWidth}, height:{originalHeight}"); | |
SvgImageSource svgImage = new SvgImageSource | |
{ | |
RasterizePixelWidth = originalWidth, | |
RasterizePixelHeight = originalHeight, | |
}; | |
await svgImage.SetSourceAsync(fs); | |
return svgImage; | |
static double GetValue(in string source) | |
{ | |
if (!string.IsNullOrEmpty(source)) | |
{ | |
Regex pattern = new Regex(@"(?<value>(\d|\.)+)"); | |
Match match = pattern.Match(source); | |
if (match.Success && double.TryParse(match.Groups["value"].Value, out double value)) | |
return value; | |
} | |
return 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment