使用 c# 修改 SVG 文件的属性并将其设置为 uwp 中图像元素的源

问题描述 投票:0回答:1
string svgFilePath = "ms-appx:///Assets/Chart.svg";
XNamespace svgNamespace = "http://www.w3.org/2000/svg";

StorageFile svgFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(svgFilePath));
XDocument svgDocument;

using (IRandomAccessStream fileStream = await svgFile.OpenAsync(FileAccessMode.Read))
{
    using (StreamReader reader = new StreamReader(fileStream.AsStream()))
    {
        string svgContent = await reader.ReadToEndAsync();
        svgDocument = XDocument.Parse(svgContent);

        // Modify the SVG content as needed
        foreach (var pathElement in svgDocument.Descendants(svgNamespace + "path"))
        {
            XAttribute nameAttribute = pathElement.Attribute("name");
            XAttribute fillAttribute = pathElement.Attribute("fill");

            string attributeName = nameAttribute.Value;

            if (svgColorMap.ContainsKey(attributeName) && fillAttribute != null)
            {
                fillAttribute.Value = svgColorMap[attributeName];

                XAttribute strokeAttribute = pathElement.Attribute("stroke");

                if (attributeName.Equals("Column4") && strokeAttribute != null)
                {
                    strokeAttribute.Value = svgColorMap[attributeName];
                }
            }
        }
    }

    // Convert the modified SVG content back to a stream
    using (MemoryStream memoryStream = new MemoryStream())
    {
        svgDocument.Save(memoryStream);
        memoryStream.Position = 0;

        SvgImageSource svgImage = new SvgImageSource();
            
        //svgImage.RasterizePixelWidth = (int)svgDocument.Root.Attribute("width");
        //svgImage.RasterizePixelHeight = (int)svgDocument.Root.Attribute("height");

        await svgImage.SetSourceAsync(memoryStream.AsRandomAccessStream());

        // Set the Image control directly as the content of your SVGImage2
        SVGImage2.Source = svgImage;
    }
}

我尝试将修改后的 SVG 文档转换为内存流并将其设置为图像源。但除非我给出 rasterizepixel 宽度和高度,否则它不会显示,这会产生模糊的图像。

c# xaml svg uwp uwp-xaml
1个回答
0
投票

根据文件

由于没有明确指定高度或宽度,因此 应用程序布局将决定 SVG 的适当大小 解码于。

建议您设置SVG的宽度和高度。如果图像模糊,可以先将修改后的svg图像导出保存,看看是否正常。

© www.soinside.com 2019 - 2024. All rights reserved.