SvgTransformConverter.cs 9.33 KB
Newer Older
davescriven's avatar
davescriven committed
1
2
3
4
5
6
7
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;
using System.Text.RegularExpressions;
8
using System.Globalization;
9
using System.Linq;
davescriven's avatar
davescriven committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23

namespace Svg.Transforms
{
    public class SvgTransformConverter : TypeConverter
    {
        private static IEnumerable<string> SplitTransforms(string transforms)
        {
            int transformEnd = 0;

            for (int i = 0; i < transforms.Length; i++)
            {
                if (transforms[i] == ')')
                {
                    yield return transforms.Substring(transformEnd, i - transformEnd + 1).Trim();
24
25
                    while (i < transforms.Length && !char.IsLetter(transforms[i])) i++;
                    transformEnd = i;
davescriven's avatar
davescriven committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
                }
            }
        }

        /// <summary>
        /// Converts the given object to the type of this converter, using the specified context and culture information.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param>
        /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture.</param>
        /// <param name="value">The <see cref="T:System.Object"/> to convert.</param>
        /// <returns>
        /// An <see cref="T:System.Object"/> that represents the converted value.
        /// </returns>
        /// <exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception>
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is string)
            {
                SvgTransformCollection transformList = new SvgTransformCollection();

                string[] parts;
                string contents;
                string transformName;

                foreach (string transform in SvgTransformConverter.SplitTransforms((string)value))
                {
                    if (string.IsNullOrEmpty(transform))
                        continue;

                    parts = transform.Split('(', ')');
                    transformName = parts[0].Trim();
                    contents = parts[1].Trim();

                    switch (transformName)
                    {
                        case "translate":
62
                            string[] coords = contents.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
63

64
                            if (coords.Length == 0 || coords.Length > 2)
65
                            {
66
                                throw new FormatException("Translate transforms must be in the format 'translate(x [,y])'");
67
68
                            }

69
                            float x = float.Parse(coords[0].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture);
70
71
72
73
74
75
76
77
78
                            if (coords.Length > 1)
                            {
                                float y = float.Parse(coords[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture);
                                transformList.Add(new SvgTranslate(x, y));
                            }
                            else
                            {
                                transformList.Add(new SvgTranslate(x));
                            }
davescriven's avatar
davescriven committed
79
80
                            break;
                        case "rotate":
81
82
83
84
85
86
87
88
89
                            string[] args = contents.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

                            if (args.Length != 1 && args.Length != 3)
                            {
                                throw new FormatException("Rotate transforms must be in the format 'rotate(angle [cx cy ])'");
                            }

                            float angle = float.Parse(args[0], NumberStyles.Float, CultureInfo.InvariantCulture);

90
                            if (args.Length == 1)
91
92
93
94
95
96
97
98
99
100
                            {
                                transformList.Add(new SvgRotate(angle));
                            }
                            else
                            {
                                float cx = float.Parse(args[1], NumberStyles.Float, CultureInfo.InvariantCulture);
                                float cy = float.Parse(args[2], NumberStyles.Float, CultureInfo.InvariantCulture);

                                transformList.Add(new SvgRotate(angle, cx, cy));
                            }
davescriven's avatar
davescriven committed
101
102
                            break;
                        case "scale":
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
                            string[] scales = contents.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

                            if (scales.Length == 0 || scales.Length > 2)
                            {
                                throw new FormatException("Scale transforms must be in the format 'scale(x [,y])'");
                            }

                            float sx = float.Parse(scales[0].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture);

                            if (scales.Length > 1)
                            {
                                float sy = float.Parse(scales[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture);
                                transformList.Add(new SvgScale(sx, sy));
                            }
                            else
                            {
                                transformList.Add(new SvgScale(sx));
                            }

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
                            break;
                        case "matrix":
                            string[] points = contents.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

                            if (points.Length != 6)
                            {
                                throw new FormatException("Matrix transforms must be in the format 'matrix(m11, m12, m21, m22, dx, dy)'");
                            }

                            List<float> mPoints = new List<float>();
                            foreach (string point in points)
                            {
                                mPoints.Add(float.Parse(point.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture));
                            }

                            transformList.Add(new SvgMatrix(mPoints));
                            break;
                        case "shear":
                            string[] shears = contents.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

                            if (shears.Length == 0 || shears.Length > 2)
                            {
                                throw new FormatException("Shear transforms must be in the format 'shear(x [,y])'");
                            }

                            float hx = float.Parse(shears[0].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture);

                            if (shears.Length > 1)
                            {
                                float hy = float.Parse(shears[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture);
                                transformList.Add(new SvgShear(hx, hy));
                            }
                            else
                            {
                                transformList.Add(new SvgShear(hx));
                            }

                            break;
                        case "skewX":
                            float ax = float.Parse(contents, NumberStyles.Float, CultureInfo.InvariantCulture);
                            transformList.Add(new SvgSkew(ax, 0));
                            break;
                        case "skewY":
                            float ay = float.Parse(contents, NumberStyles.Float, CultureInfo.InvariantCulture);
                            transformList.Add(new SvgSkew(0, ay));
davescriven's avatar
davescriven committed
167
168
169
170
171
172
173
174
175
                            break;
                    }
                }

                return transformList;
            }

            return base.ConvertFrom(context, culture, value);
        }
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }

            return base.CanConvertFrom(context, sourceType);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                return true;
            }

            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                var transforms = value as SvgTransformCollection;

                if (transforms != null)
                {
Tebjan Halm's avatar
Tebjan Halm committed
205
                    return string.Join(" ", transforms.Select(t => t.WriteToString()).ToArray());
206
207
208
209
210
                }
            }

            return base.ConvertTo(context, culture, value, destinationType);
        }
davescriven's avatar
davescriven committed
211
    }
212
}