New to Telerik UI for WinForms? Download free 30-day trial

Customize the Color for SVG Images

Environment

Product Version Product Author
2021.3.119 SVG Images for WinForms Desislava Yordanova

Description

Telerik UI for WinForms suite offers support for vector images. This article demonstrates a sample approach how you can change the color used in the vector image.

customize-the-color-for-svg-images

Solution

First, you need to open the svg file in Notepad and have a look of its definition and what elements are contained, e.g. paths, polygons, etc. Then, you can look for the respective elements in the RadSvgImage and customize the respective Stroke or Fill:

It is important to note that depending on the internal structure of the svg image you may need to customize more internal elements.


public partial class RadForm1 : Telerik.WinControls.UI.RadForm
{
    RadSvgImage miniSVG = null;
    RadPictureBox radPictureBox1 = new RadPictureBox() { Size = new Size(150,100), Location = new Point(10,10) };
    RadColorSelector radColorSelector1 = new RadColorSelector() { Location = new Point(200,10) }; 

    public RadForm1()
    {
        InitializeComponent(); 
        radPictureBox1.Location = new Point(10,10);
        this.Controls.Add(this.radPictureBox1);
        miniSVG = RadSvgImage.FromFile(@"..\..\mini.svg");
        this.radPictureBox1.SvgImage = miniSVG;
        this.Controls.Add(this.radColorSelector1); 
        radColorSelector1.ColorChanged += radColorSelector1_ColorChanged;
    }

    private void radColorSelector1_ColorChanged(object sender, ColorChangedEventArgs args)
    {
        IEnumerable<SvgPath> paths = miniSVG.Document.Children.FindSvgElementsOf<SvgPath>();
        IEnumerable<SvgPolygon> polygons = miniSVG.Document.Children.FindSvgElementsOf<SvgPolygon>();
        foreach (SvgPath path in paths)
        { 
            path.Stroke = new SvgColourServer(args.SelectedColor);
            path.Fill = new SvgColourServer(args.SelectedColor);
        }

        foreach (SvgPolygon polygon in polygons)
        { 
            polygon.Stroke = new SvgColourServer(args.SelectedColor);
            polygon.Fill = new SvgColourServer(args.SelectedColor);
        }

        // clear the cache of RadSvgImage
        miniSVG.ClearCache();
        this.radPictureBox1.SvgImage = null;
        this.radPictureBox1.SvgImage = miniSVG;
    }
}