在xamarin中更改svg内部的颜色路径



我有一个简化的svg文件,其大意是我想更改svg文件中某些路径的颜色。

<?xml..>
<svg..>
<g >
<path id="cp1589"style="fill:none;stroke:#000000;" d="m 547.96,1140.. z" />
</g>
</svg>

这就是简化的计划.xaml

<?xml ..>
<ContentPage ..>
<abstractions:SvgImage Grid.Row="0"
Grid.Column="0"
SvgAssembly="{Binding SvgAssembly}"
SvgPath="{Binding SvgPath}"/>
</ContentPage>

简化的Plan.xaml.cs

public partial class Plan : ContentPage
{
public string SvgPath { get; set; }
public Assembly SvgAssembly { get; set; }
public Plan()
{
InitializeComponent();
SvgPath = "Test.Images.Plan.svg";
SvgAssembly = typeof(App).GetTypeInfo().Assembly;
BindingContext = this;
Stream stream = SvgAssembly.GetManifestResourceStream(SvgPath);
XmlDocument xml = new XmlDocument();
xml.Load(stream);
var circle = xml.GetElementsByTagName("path");
for (int i = 0; i < circle.Count; i++)
{
var path = circle[i].Attributes;
for (int j = 0; j < path.Count; j++)
{
XmlNode node = path[j].SelectSingleNode(".");
if (path[j].Name.Equals("style"))
node.Value = "fill: rgb(0, 128, 0);";                                  
}
}
//xml.Save(stream);
}
}

问题是,颜色没有变化。。

我们无法用SvgImage做到这一点。

当我们使用SvgImage时,我们必须将svg文件的Build Action设置为Embedded Resource。https://github.com/paulpatarinski/Xamarin.Forms.Plugins/tree/master/SVG

但是嵌入的资源被编译到我们的exe/dll中,并不意味着要修改。在运行时期间更改嵌入的资源文件

我已经尝试将流保存到内部存储中,并使用INotifyPropertyChanged更新SvgPath。但就像我第一次说的那样,我们保存的svg必须是Embedded Resource。我们不能那样做。下面是我尝试从存储加载时的错误。

System.AggregateException: 'One or more errors occurred. (Error retrieving /data/user/0/com.companyname.app4/files/file1.svg make sure Build Action is Embedded Resource)'

您可以使用FFImageLoading。

(Nuget包:Xamarin.FImageLoading,Xamarin.FFImageLoading.Forms,Xamari.FImageLoading.Svg和Xamarin.FFImageLoading.Svg.Forms(

首先,您必须对svg进行更改,并获得生成的svg内容:

Stream stream = SvgAssembly.GetManifestResourceStream(SvgPath);
XmlDocument xml = new XmlDocument();
xml.Load(stream);
...
using MemoryStream memoryStream = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings{
Indent = true,
Encoding = Encoding.UTF8
};
using XmlWriter writer = XmlWriter.Create(memoryStream, settings);
xml.WriteContentTo(writer);
writer.Flush();
writer.Close();
string modifiedSvg = Encoding.UTF8.GetString(memoryStream.ToArray());

然后可以使用FFImageLoading创建一个新的SVG。

SvgImageSource.FromSvgString(modifiedSvg)

此ImageSource可以显示,例如使用SvgCachedImage。

您可以使用FFImageLoading根据程序条件(真/假(对svg图像进行着色,您可以更改着色。

最新更新