简体   繁体   中英

Xamarin Xam.Plugins.Forms.Svg change SvgPath to rerender the image

I use Xam.Plugins.Forms.Svg to support svg images. I need to change the image, so I tried:

binding in xaml :

<abstractions:SvgImage
    SvgPath="{Binding CurrentWeather.IconSource, StringFormat='Umbrella.Images.{0:F0}.svg'}"
    ....
    />

to change it directly from C#:

icon.SvgPath = "Umbrella.Images." + currentWeather.IconSource + ".svg";

The SvgPath attribute does change, but the image doesn't rerender.

Is there any solution to this?

It is an issue in the way the renderers are written, you would need to create a new SvgImage object and replace the current on in your page the way the renderers work in order for the static Image to be updated from a new SVG file.

You can patch the renderers by overriding the OnElementPropertyChanged event and respond to SvgPath PropertyName changes:

iOS Example:

protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    base.OnElementPropertyChanged(sender, e);
    if (e.PropertyName == "SvgPath")
    {
        var svgStream = _formsControl.SvgAssembly.GetManifestResourceStream(_formsControl.SvgPath);
        var reader = new SvgReader(new StreamReader(svgStream), new StylesParser(new ValuesParser()), new ValuesParser());
        var graphics = reader.Graphic;
        var canvas = new ApplePlatform().CreateImageCanvas(graphics.Size);
        graphics.Draw(canvas);
        var image = canvas.GetImage();
        var uiImage = image.GetUIImage();
        Control.Image = uiImage;
    }
}

Ref: https://github.com/paulpatarinski/Xamarin.Forms.Plugins/blob/eab230fcf4158a288387727c15903a954e01cdaa/SVG/SVG/SVG.Forms.Plugin.Android/SvgImageRenderer.cs

Ref: https://github.com/paulpatarinski/Xamarin.Forms.Plugins/blob/eab230fcf4158a288387727c15903a954e01cdaa/SVG/SVG/SVG.Forms.Plugin.iOS/SvgImageRenderer.cs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM