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

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

James Welle's avatar
James Welle committed
26
        [SvgAttribute("y1")]
davescriven's avatar
davescriven committed
27
28
        public SvgUnit Y1
        {
James Welle's avatar
James Welle committed
29
30
31
32
            get
            {
                return this.Attributes.GetAttribute<SvgUnit>("y1");
            }
davescriven's avatar
davescriven committed
33
34
            set
            {
James Welle's avatar
James Welle committed
35
                this.Attributes["y1"] = value;
davescriven's avatar
davescriven committed
36
37
38
            }
        }

James Welle's avatar
James Welle committed
39
        [SvgAttribute("x2")]
davescriven's avatar
davescriven committed
40
41
        public SvgUnit X2
        {
James Welle's avatar
James Welle committed
42
43
44
45
            get
            {
                return this.Attributes.GetAttribute<SvgUnit>("x2");
            }
davescriven's avatar
davescriven committed
46
47
            set
            {
James Welle's avatar
James Welle committed
48
                Attributes["x2"] = value;
davescriven's avatar
davescriven committed
49
50
51
            }
        }

James Welle's avatar
James Welle committed
52
        [SvgAttribute("y2")]
davescriven's avatar
davescriven committed
53
54
        public SvgUnit Y2
        {
James Welle's avatar
James Welle committed
55
56
57
58
            get
            {
                return this.Attributes.GetAttribute<SvgUnit>("y2");
            }
davescriven's avatar
davescriven committed
59
60
            set
            {
James Welle's avatar
James Welle committed
61
62
63
64
65
66
67
68
69
70
                this.Attributes["y2"] = value;
            }
        }

        private bool IsInvalid
        {
            get
            {
                // Need at least 2 colours to do the gradient fill
                return this.Stops.Count < 2;
davescriven's avatar
davescriven committed
71
72
73
74
75
            }
        }

        public SvgLinearGradientServer()
        {
James Welle's avatar
James Welle committed
76
77
78
79
80
81
            X1 = new SvgUnit(SvgUnitType.Percentage, 0F);
            Y1 = new SvgUnit(SvgUnitType.Percentage, 0F);
            X2 = new SvgUnit(SvgUnitType.Percentage, 100F);
            Y2 = new SvgUnit(SvgUnitType.Percentage, 0F);
        }

Eric Domke's avatar
Eric Domke committed
82
        public override Brush GetBrush(SvgVisualElement renderingElement, ISvgRenderer renderer, float opacity)
James Welle's avatar
James Welle committed
83
        {
84
            LoadStops(renderingElement);
James Welle's avatar
James Welle committed
85
86
87
88
89
            if (IsInvalid)
            {
                return null;
            }

90
91
            try
            {
Eric Domke's avatar
Eric Domke committed
92
                if (this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox) renderer.SetBoundable(renderingElement);
James Welle's avatar
James Welle committed
93

94
95
                var specifiedStart = CalculateStart(renderer);
                var specifiedEnd = CalculateEnd(renderer);
James Welle's avatar
James Welle committed
96

97
98
                var effectiveStart = specifiedStart;
                var effectiveEnd = specifiedEnd;
James Welle's avatar
James Welle committed
99

100
101
102
103
104
105
                if (NeedToExpandGradient(renderingElement, specifiedStart, specifiedEnd))
                {
                    var expansion = ExpandGradient(renderingElement, specifiedStart, specifiedEnd);
                    effectiveStart = expansion.StartPoint;
                    effectiveEnd = expansion.EndPoint;
                }
James Welle's avatar
James Welle committed
106

107
108
109
110
111
112
113
                return new LinearGradientBrush(effectiveStart, effectiveEnd, System.Drawing.Color.Transparent, System.Drawing.Color.Transparent)
                {
                    InterpolationColors = CalculateColorBlend(renderer, opacity, specifiedStart, effectiveStart, specifiedEnd, effectiveEnd),
                    WrapMode = WrapMode.TileFlipX
                };
            }
            finally
James Welle's avatar
James Welle committed
114
            {
115
116
                if (this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox) renderer.PopBoundable();
            }
James Welle's avatar
James Welle committed
117
118
        }

Eric Domke's avatar
Eric Domke committed
119
        private PointF CalculateStart(ISvgRenderer renderer)
James Welle's avatar
James Welle committed
120
        {
121
            return TransformPoint(SvgUnit.GetDevicePointOffset(this.X1, this.Y1, renderer, this));
davescriven's avatar
davescriven committed
122
123
        }

Eric Domke's avatar
Eric Domke committed
124
        private PointF CalculateEnd(ISvgRenderer renderer)
davescriven's avatar
davescriven committed
125
        {
126
            return TransformPoint(SvgUnit.GetDevicePointOffset(this.X2, this.Y2, renderer, this));
davescriven's avatar
davescriven committed
127
128
        }

James Welle's avatar
James Welle committed
129
        private bool NeedToExpandGradient(ISvgBoundable boundable, PointF specifiedStart, PointF specifiedEnd)
davescriven's avatar
davescriven committed
130
        {
James Welle's avatar
James Welle committed
131
            return SpreadMethod == SvgGradientSpreadMethod.Pad && (boundable.Bounds.Contains(specifiedStart) || boundable.Bounds.Contains(specifiedEnd));
davescriven's avatar
davescriven committed
132
133
        }

134
135
136
137
138
139
        public struct GradientPoints
        {
            public PointF StartPoint;
            public PointF EndPoint;

            public GradientPoints(PointF startPoint, PointF endPoint)
140
            {
141
142
143
144
145
146
                this.StartPoint = startPoint;
                this.EndPoint = endPoint;
            }
        }

        private GradientPoints ExpandGradient(ISvgBoundable boundable, PointF specifiedStart, PointF specifiedEnd)
davescriven's avatar
davescriven committed
147
        {
James Welle's avatar
James Welle committed
148
            if (!NeedToExpandGradient(boundable, specifiedStart, specifiedEnd))
149
            {
James Welle's avatar
James Welle committed
150
                Debug.Fail("Unexpectedly expanding gradient when not needed!");
151
                return new GradientPoints(specifiedStart, specifiedEnd);
152
            }
davescriven's avatar
davescriven committed
153

James Welle's avatar
James Welle committed
154
155
156
157
158
159
160
161
162
163
164
165
            var specifiedLength = CalculateDistance(specifiedStart, specifiedEnd);
            var specifiedUnitVector = new PointF((specifiedEnd.X - specifiedStart.X) / (float)specifiedLength, (specifiedEnd.Y - specifiedStart.Y) / (float)specifiedLength);

            var effectiveStart = specifiedStart;
            var effectiveEnd = specifiedEnd;

            var elementDiagonal = (float)CalculateDistance(new PointF(boundable.Bounds.Left, boundable.Bounds.Top), new PointF(boundable.Bounds.Right, boundable.Bounds.Bottom));

            var expandedStart = MovePointAlongVector(effectiveStart, specifiedUnitVector, -elementDiagonal);
            var expandedEnd = MovePointAlongVector(effectiveEnd, specifiedUnitVector, elementDiagonal);

            var intersectionPoints = new LineF(expandedStart.X, expandedStart.Y, expandedEnd.X, expandedEnd.Y).Intersection(boundable.Bounds);
davescriven's avatar
davescriven committed
166

James Welle's avatar
James Welle committed
167
            if (boundable.Bounds.Contains(specifiedStart))
davescriven's avatar
davescriven committed
168
            {
James Welle's avatar
James Welle committed
169
170
171
172
173
174
175
                effectiveStart = CalculateClosestIntersectionPoint(expandedStart, intersectionPoints);

                effectiveStart = MovePointAlongVector(effectiveStart, specifiedUnitVector, -1);
            }

            if (boundable.Bounds.Contains(specifiedEnd))
            {
Eric Domke's avatar
Eric Domke committed
176
                effectiveEnd = CalculateClosestIntersectionPoint(expandedEnd, intersectionPoints);
James Welle's avatar
James Welle committed
177
178
179
180

                effectiveEnd = MovePointAlongVector(effectiveEnd, specifiedUnitVector, 1);
            }

181
            return new GradientPoints(effectiveStart, effectiveEnd);
James Welle's avatar
James Welle committed
182
183
        }

Eric Domke's avatar
Eric Domke committed
184
        private ColorBlend CalculateColorBlend(ISvgRenderer renderer, float opacity, PointF specifiedStart, PointF effectiveStart, PointF specifiedEnd, PointF effectiveEnd)
James Welle's avatar
James Welle committed
185
        {
186
            var colorBlend = GetColorBlend(renderer, opacity, false);
James Welle's avatar
James Welle committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202

            var startDelta = CalculateDistance(specifiedStart, effectiveStart);
            var endDelta = CalculateDistance(specifiedEnd, effectiveEnd);

            if (!(startDelta > 0) && !(endDelta > 0))
            {
                return colorBlend;
            }

            var specifiedLength = CalculateDistance(specifiedStart, specifiedEnd);
            var specifiedUnitVector = new PointF((specifiedEnd.X - specifiedStart.X) / (float)specifiedLength, (specifiedEnd.Y - specifiedStart.Y) / (float)specifiedLength);

            var effectiveLength = CalculateDistance(effectiveStart, effectiveEnd);

            for (var i = 0; i < colorBlend.Positions.Length; i++)
            {
203
                var originalPoint = MovePointAlongVector(specifiedStart, specifiedUnitVector, (float)specifiedLength * colorBlend.Positions[i]);
davescriven's avatar
davescriven committed
204

James Welle's avatar
James Welle committed
205
206
                var distanceFromEffectiveStart = CalculateDistance(effectiveStart, originalPoint);

207
                colorBlend.Positions[i] = (float)Math.Round(Math.Max(0F, Math.Min((distanceFromEffectiveStart / effectiveLength), 1.0F)), 5);
James Welle's avatar
James Welle committed
208
209
210
211
212
213
            }

            if (startDelta > 0)
            {
                colorBlend.Positions = new[] { 0F }.Concat(colorBlend.Positions).ToArray();
                colorBlend.Colors = new[] { colorBlend.Colors.First() }.Concat(colorBlend.Colors).ToArray();
davescriven's avatar
davescriven committed
214
            }
James Welle's avatar
James Welle committed
215
216

            if (endDelta > 0)
davescriven's avatar
davescriven committed
217
            {
James Welle's avatar
James Welle committed
218
219
                colorBlend.Positions = colorBlend.Positions.Concat(new[] { 1F }).ToArray();
                colorBlend.Colors = colorBlend.Colors.Concat(new[] { colorBlend.Colors.Last() }).ToArray();
davescriven's avatar
davescriven committed
220
221
            }

James Welle's avatar
James Welle committed
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
            return colorBlend;
        }

        private static PointF CalculateClosestIntersectionPoint(PointF sourcePoint, IList<PointF> targetPoints)
        {
            Debug.Assert(targetPoints.Count == 2, "Unexpected number of intersection points!");

            return CalculateDistance(sourcePoint, targetPoints[0]) < CalculateDistance(sourcePoint, targetPoints[1]) ? targetPoints[0] : targetPoints[1];
        }

        private static PointF MovePointAlongVector(PointF start, PointF unitVector, float distance)
        {
            return start + new SizeF(unitVector.X * distance, unitVector.Y * distance);
        }

        public override SvgElement DeepCopy()
        {
            return DeepCopy<SvgLinearGradientServer>();
        }

        public override SvgElement DeepCopy<T>()
        {
            var newObj = base.DeepCopy<T>() as SvgLinearGradientServer;
            newObj.X1 = this.X1;
            newObj.Y1 = this.Y1;
            newObj.X2 = this.X2;
            newObj.Y2 = this.Y2;
            return newObj;
davescriven's avatar
davescriven committed
250
251

        }
252

James Welle's avatar
James Welle committed
253
254
255
256
257
258
259
260
261
262
        private sealed class LineF
        {
            private float X1
            {
                get;
                set;
            }

            private float Y1
            {
263
                get;
James Welle's avatar
James Welle committed
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
                set;
            }

            private float X2
            {
                get;
                set;
            }

            private float Y2
            {
                get;
                set;
            }

            public LineF(float x1, float y1, float x2, float y2)
            {
                X1 = x1;
                Y1 = y1;
                X2 = x2;
                Y2 = y2;
            }

            public List<PointF> Intersection(RectangleF rectangle)
            {
                var result = new List<PointF>();

                AddIfIntersect(this, new LineF(rectangle.X, rectangle.Y, rectangle.Right, rectangle.Y), result);
                AddIfIntersect(this, new LineF(rectangle.Right, rectangle.Y, rectangle.Right, rectangle.Bottom), result);
                AddIfIntersect(this, new LineF(rectangle.Right, rectangle.Bottom, rectangle.X, rectangle.Bottom), result);
                AddIfIntersect(this, new LineF(rectangle.X, rectangle.Bottom, rectangle.X, rectangle.Y), result);

                return result;
            }

Eric Domke's avatar
Eric Domke committed
299
            /// <remarks>http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=geometry2</remarks>
James Welle's avatar
James Welle committed
300
301
            private PointF? Intersection(LineF other)
            {
Eric Domke's avatar
Eric Domke committed
302
                const int precision = 8;
James Welle's avatar
James Welle committed
303

Eric Domke's avatar
Eric Domke committed
304
305
306
                var a1 = (double)Y2 - Y1;
                var b1 = (double)X1 - X2;
                var c1 = a1 * X1 + b1 * Y1;
James Welle's avatar
James Welle committed
307

Eric Domke's avatar
Eric Domke committed
308
309
310
311
312
313
                var a2 = (double)other.Y2 - other.Y1;
                var b2 = (double)other.X1 - other.X2;
                var c2 = a2 * other.X1 + b2 * other.Y1;

                var det = a1 * b2 - a2 * b1;
                if (det == 0)
James Welle's avatar
James Welle committed
314
315
316
                {
                    return null;
                }
Eric Domke's avatar
Eric Domke committed
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
                else
                {
                    var xi = (b2 * c1 - b1 * c2) / det;
                    var yi = (a1 * c2 - a2 * c1) / det;

                    if (Math.Round(Math.Min(X1, X2), precision) <= Math.Round(xi, precision) &&
                        Math.Round(xi, precision) <= Math.Round(Math.Max(X1, X2), precision) &&
                        Math.Round(Math.Min(Y1, Y2), precision) <= Math.Round(yi, precision) &&
                        Math.Round(yi, precision) <= Math.Round(Math.Max(Y1, Y2), precision) &&
                        Math.Round(Math.Min(other.X1, other.X2), precision) <= Math.Round(xi, precision) &&
                        Math.Round(xi, precision) <= Math.Round(Math.Max(other.X1, other.X2), precision) &&
                        Math.Round(Math.Min(other.Y1, other.Y2), precision) <= Math.Round(yi, precision) &&
                        Math.Round(yi, precision) <= Math.Round(Math.Max(other.Y1, other.Y2), precision))
                    {
                        return new PointF((float)xi, (float)yi);
                    }
                    else
                    {
                        return null;
                    }
                }
James Welle's avatar
James Welle committed
338

339

Eric Domke's avatar
Eric Domke committed
340
341
342
                //var a1 = Y2 - Y1;
                //var b1 = X1 - X2;
                //var c1 = X2 * Y1 - X1 * Y2;
343

Eric Domke's avatar
Eric Domke committed
344
345
                //var r3 = a1 * other.X1 + b1 * other.Y1 + c1;
                //var r4 = a1 * other.X2 + b1 * other.Y2 + c1;
James Welle's avatar
James Welle committed
346

Eric Domke's avatar
Eric Domke committed
347
348
349
350
                //if (r3 != 0 && r4 != 0 && Math.Sign(r3) == Math.Sign(r4))
                //{
                //    return null;
                //}
James Welle's avatar
James Welle committed
351

Eric Domke's avatar
Eric Domke committed
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
                //var a2 = other.Y2 - other.Y1;
                //var b2 = other.X1 - other.X2;
                //var c2 = other.X2 * other.Y1 - other.X1 * other.Y2;

                //var r1 = a2 * X1 + b2 * Y1 + c2;
                //var r2 = a2 * X2 + b2 * Y2 + c2;

                //if (r1 != 0 && r2 != 0 && Math.Sign(r1) == Math.Sign(r2))
                //{
                //    return (null);
                //}

                //var denom = a1 * b2 - a2 * b1;

                //if (denom == 0)
                //{
                //    return null;
                //}
370

Eric Domke's avatar
Eric Domke committed
371
                //var offset = denom < 0 ? -denom / 2 : denom / 2;
372

Eric Domke's avatar
Eric Domke committed
373
374
                //var num = b1 * c2 - b2 * c1;
                //var x = (num < 0 ? num - offset : num + offset) / denom;
375

Eric Domke's avatar
Eric Domke committed
376
377
                //num = a2 * c1 - a1 * c2;
                //var y = (num < 0 ? num - offset : num + offset) / denom;
James Welle's avatar
James Welle committed
378

Eric Domke's avatar
Eric Domke committed
379
                //return new PointF(x, y);
James Welle's avatar
James Welle committed
380
381
382
383
384
385
386
387
388
389
390
391
            }

            private static void AddIfIntersect(LineF first, LineF second, ICollection<PointF> result)
            {
                var intersection = first.Intersection(second);

                if (intersection != null)
                {
                    result.Add(intersection.Value);
                }
            }
        }
davescriven's avatar
davescriven committed
392
393
    }
}