SvgRadialGradientServer.cs 10.7 KB
Newer Older
James Welle's avatar
James Welle committed
1
2
using System;
using System.Diagnostics;
davescriven's avatar
davescriven committed
3
using System.Drawing;
Eric Domke's avatar
Eric Domke committed
4
using System.Collections.Generic;
davescriven's avatar
davescriven committed
5
using System.Drawing.Drawing2D;
James Welle's avatar
James Welle committed
6
using System.Linq;
davescriven's avatar
davescriven committed
7
8
9

namespace Svg
{
10
    [SvgElement("radialGradient")]
davescriven's avatar
davescriven committed
11
12
13
14
15
    public sealed class SvgRadialGradientServer : SvgGradientServer
    {
        [SvgAttribute("cx")]
        public SvgUnit CenterX
        {
James Welle's avatar
James Welle committed
16
17
18
19
20
21
22
23
            get
            {
                return this.Attributes.GetAttribute<SvgUnit>("cx");
            }
            set
            {
                this.Attributes["cx"] = value;
            }
davescriven's avatar
davescriven committed
24
25
26
27
28
        }

        [SvgAttribute("cy")]
        public SvgUnit CenterY
        {
James Welle's avatar
James Welle committed
29
30
31
32
33
34
35
36
            get
            {
                return this.Attributes.GetAttribute<SvgUnit>("cy");
            }
            set
            {
                this.Attributes["cy"] = value;
            }
davescriven's avatar
davescriven committed
37
38
39
40
41
        }

        [SvgAttribute("r")]
        public SvgUnit Radius
        {
James Welle's avatar
James Welle committed
42
43
44
45
46
47
48
49
            get
            {
                return this.Attributes.GetAttribute<SvgUnit>("r");
            }
            set
            {
                this.Attributes["r"] = value;
            }
davescriven's avatar
davescriven committed
50
51
52
53
54
        }

        [SvgAttribute("fx")]
        public SvgUnit FocalX
        {
55
56
57
58
59
60
61
62
63
64
65
            get
            {
                var value = this.Attributes.GetAttribute<SvgUnit>("fx");

                if (value.IsEmpty || value.IsNone)
                {
                    value = this.CenterX;
                }

                return value;
            }
James Welle's avatar
James Welle committed
66
67
68
69
            set
            {
                this.Attributes["fx"] = value;
            }
davescriven's avatar
davescriven committed
70
71
72
73
74
        }

        [SvgAttribute("fy")]
        public SvgUnit FocalY
        {
75
76
77
78
79
80
81
82
83
84
85
            get
            {
                var value = this.Attributes.GetAttribute<SvgUnit>("fy");

                if (value.IsEmpty || value.IsNone)
                {
                    value = this.CenterY;
                }

                return value;
            }
James Welle's avatar
James Welle committed
86
87
88
89
            set
            {
                this.Attributes["fy"] = value;
            }
davescriven's avatar
davescriven committed
90
91
92
93
        }

        public SvgRadialGradientServer()
        {
James Welle's avatar
James Welle committed
94
95
96
            CenterX = new SvgUnit(SvgUnitType.Percentage, 50F);
            CenterY = new SvgUnit(SvgUnitType.Percentage, 50F);
            Radius = new SvgUnit(SvgUnitType.Percentage, 50F);
davescriven's avatar
davescriven committed
97
98
        }

Eric Domke's avatar
Eric Domke committed
99
100
        private object _lockObj = new Object();

101
        public override Brush GetBrush(SvgVisualElement renderingElement, SvgRenderer renderer, float opacity)
davescriven's avatar
davescriven committed
102
        {
103
            LoadStops(renderingElement);
James Welle's avatar
James Welle committed
104

105
            try
106
            {
107
                if (this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox) renderer.Boundable(renderingElement);
Eric Domke's avatar
Eric Domke committed
108
109
                
                // Calculate the path and transform it appropriately
110
                var origin = renderer.Boundable().Location;
Eric Domke's avatar
Eric Domke committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
                var center = new PointF(origin.X + CenterX.ToDeviceValue(renderer, UnitRenderingType.HorizontalOffset, this),
                                         origin.Y + CenterY.ToDeviceValue(renderer, UnitRenderingType.VerticalOffset, this));
                var specifiedRadius = Radius.ToDeviceValue(renderer, UnitRenderingType.Other, this);
                var path = new GraphicsPath();
                path.AddEllipse(
                    origin.X + center.X - specifiedRadius, origin.Y + center.Y - specifiedRadius,
                    specifiedRadius * 2, specifiedRadius * 2
                );
                path.Transform(EffectiveGradientTransform);


                // Calculate any required scaling
                var scale = CalcScale(renderingElement.Bounds, path);

                // Get the color blend and any tweak to the scaling
                var blend = CalculateColorBlend(renderer, opacity, scale, out scale);

                // Transform the path based on the scaling
                var gradBounds = path.GetBounds();
                var transCenter = new PointF(gradBounds.Left + gradBounds.Width / 2, gradBounds.Top + gradBounds.Height / 2);
                var scaleMat = new Matrix();
                scaleMat.Translate(-1 * transCenter.X, -1 * transCenter.Y, MatrixOrder.Append);
                scaleMat.Scale(scale, scale, MatrixOrder.Append);
                scaleMat.Translate(transCenter.X, transCenter.Y, MatrixOrder.Append);
                path.Transform(scaleMat);

                // calculate the brush
                var brush = new PathGradientBrush(path);
                brush.CenterPoint = CalculateFocalPoint(renderer, origin);
                brush.InterpolationColors = blend;
141
142
143
144
145
146
147

                return brush;
            }
            finally
            {
                if (this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox) renderer.PopBoundable();
            }
James Welle's avatar
James Welle committed
148
149
        }

Eric Domke's avatar
Eric Domke committed
150
151
152
153
154
155
156
157
158
159
160
        /// <summary>
        /// Determine how much (approximately) the path must be scaled to contain the rectangle
        /// </summary>
        /// <param name="bounds">Bounds that the path must contain</param>
        /// <param name="path">Path of the gradient</param>
        /// <returns>Scale factor</returns>
        /// <remarks>
        /// This method continually transforms the rectangle (fewer points) until it is contained by the path
        /// and returns the result of the search.  The scale factor is set to a constant 95%
        /// </remarks>
        private float CalcScale(RectangleF bounds, GraphicsPath path)
James Welle's avatar
James Welle committed
161
        {
Eric Domke's avatar
Eric Domke committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
            var points = new PointF[] {
                new PointF(bounds.Left, bounds.Top), 
                new PointF(bounds.Right, bounds.Top), 
                new PointF(bounds.Right, bounds.Bottom), 
                new PointF(bounds.Left, bounds.Bottom) 
            };
            var pathBounds = path.GetBounds();
            var pathCenter = new PointF(pathBounds.X + pathBounds.Width / 2, pathBounds.Y + pathBounds.Height / 2);
            var transform = new Matrix();
            transform.Translate(-1 * pathCenter.X, -1 * pathCenter.Y, MatrixOrder.Append);
            transform.Scale(.95f, .95f, MatrixOrder.Append);
            transform.Translate(pathCenter.X, pathCenter.Y, MatrixOrder.Append);

            var boundsTest = RectangleF.Inflate(bounds, 0, 0);
            while (!(path.IsVisible(points[0]) && path.IsVisible(points[1]) &&
                     path.IsVisible(points[2]) && path.IsVisible(points[3])))
            {
                transform.TransformPoints(points);
            }
            return bounds.Height / (points[2].Y - points[1].Y);
James Welle's avatar
James Welle committed
182
183
        }

184
        private PointF CalculateFocalPoint(SvgRenderer renderer, PointF origin)
James Welle's avatar
James Welle committed
185
        {
186
187
            var deviceFocalX = origin.X + FocalX.ToDeviceValue(renderer, UnitRenderingType.HorizontalOffset, this);
            var deviceFocalY = origin.Y + FocalY.ToDeviceValue(renderer, UnitRenderingType.VerticalOffset, this);
James Welle's avatar
James Welle committed
188
189
190
191
192
193
194
            var transformedFocalPoint = TransformPoint(new PointF(deviceFocalX, deviceFocalY));
            return transformedFocalPoint;
        }

        private static GraphicsPath CreateGraphicsPath(PointF origin, PointF centerPoint, float effectiveRadius)
        {
            var path = new GraphicsPath();
195

James Welle's avatar
James Welle committed
196
197
198
199
200
201
            path.AddEllipse(
                origin.X + centerPoint.X - effectiveRadius,
                origin.Y + centerPoint.Y - effectiveRadius,
                effectiveRadius * 2,
                effectiveRadius * 2
            );
202

James Welle's avatar
James Welle committed
203
            return path;
davescriven's avatar
davescriven committed
204
        }
205

Eric Domke's avatar
Eric Domke committed
206
        private ColorBlend CalculateColorBlend(SvgRenderer renderer, float opacity, float scale, out float outScale)
James Welle's avatar
James Welle committed
207
        {
208
            var colorBlend = GetColorBlend(renderer, opacity, true);
Eric Domke's avatar
Eric Domke committed
209
210
211
            float newScale;
            List<float> pos;
            List<Color> colors;
212

Eric Domke's avatar
Eric Domke committed
213
214
            outScale = scale;
            if (scale > 1)
James Welle's avatar
James Welle committed
215
            {
Eric Domke's avatar
Eric Domke committed
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
                switch (this.SpreadMethod)
                {
                    case SvgGradientSpreadMethod.Reflect:
                        newScale = (float)Math.Ceiling(scale);
                        pos = (from p in colorBlend.Positions select p / newScale).ToList();
                        colors = colorBlend.Colors.ToList();

                        for (var i = 1; i < newScale; i++)
                        {
                            if (i % 2 == 1)
                            {
                                pos.AddRange(from p in colorBlend.Positions.Reverse().Skip(1) select (1 - p + i) / newScale);
                                colors.AddRange(colorBlend.Colors.Reverse().Skip(1));
                            }
                            else
                            {
                                pos.AddRange(from p in colorBlend.Positions.Skip(1) select (p + i) / newScale);
                                colors.AddRange(colorBlend.Colors.Skip(1));
                            }
                        }

                        colorBlend.Positions = pos.ToArray();
                        colorBlend.Colors = colors.ToArray();
                        outScale = newScale;
                        break;
                    case SvgGradientSpreadMethod.Repeat:
                        newScale = (float)Math.Ceiling(scale);
                        pos = (from p in colorBlend.Positions select p / newScale).ToList();
                        colors = colorBlend.Colors.ToList();

                        for (var i = 1; i < newScale; i++)
                        {
                            pos.AddRange(from p in colorBlend.Positions select (p <= 0 ? 0.001f : p) / newScale);
                            colors.AddRange(colorBlend.Colors);
                        }

                        break;
                    default:
                        for (var i = 0; i < colorBlend.Positions.Length - 1; i++)
                        {
                            colorBlend.Positions[i] = 1 - (1 - colorBlend.Positions[i]) / scale;
                        }

                        colorBlend.Positions = new[] { 0F }.Concat(colorBlend.Positions).ToArray();
                        colorBlend.Colors = new[] { colorBlend.Colors.First() }.Concat(colorBlend.Colors).ToArray();

                        break;
                }
James Welle's avatar
James Welle committed
264
            }
265

James Welle's avatar
James Welle committed
266
267
            return colorBlend;
        }
268

James Welle's avatar
James Welle committed
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
        public override SvgElement DeepCopy()
        {
            return DeepCopy<SvgRadialGradientServer>();
        }

        public override SvgElement DeepCopy<T>()
        {
            var newObj = base.DeepCopy<T>() as SvgRadialGradientServer;

            newObj.CenterX = this.CenterX;
            newObj.CenterY = this.CenterY;
            newObj.Radius = this.Radius;
            newObj.FocalX = this.FocalX;
            newObj.FocalY = this.FocalY;

            return newObj;
        }
davescriven's avatar
davescriven committed
286
287
    }
}