SvgLinearGradientServer.cs 23.7 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, bool forStroke = false)
James Welle's avatar
James Welle committed
83
        {
84
            LoadStops(renderingElement);
Eric Domke's avatar
Eric Domke committed
85
86
87

            if (this.Stops.Count < 1) return null;
            if (this.Stops.Count == 1) 
James Welle's avatar
James Welle committed
88
            {
Eric Domke's avatar
Eric Domke committed
89
90
91
92
                var stopColor = this.Stops[0].GetColor(renderingElement); 
                int alpha = (int)((opacity * (stopColor.A/255.0f) ) * 255);
                Color colour = System.Drawing.Color.FromArgb(alpha, stopColor);
                return new SolidBrush(colour);
James Welle's avatar
James Welle committed
93
94
            }

95
96
            try
            {
Eric Domke's avatar
Eric Domke committed
97
                if (this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox) renderer.SetBoundable(renderingElement);
James Welle's avatar
James Welle committed
98

Eric Domke's avatar
Eric Domke committed
99
100
101
102
103
104
105
106
107
108
109
110
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
141
142
143
144
145
146
147
148
149
150
151
152
                var points = new PointF[] {
                    SvgUnit.GetDevicePoint(NormalizeUnit(this.X1), NormalizeUnit(this.Y1), renderer, this),
                    SvgUnit.GetDevicePoint(NormalizeUnit(this.X2), NormalizeUnit(this.Y2), renderer, this)
                };

                var bounds = renderer.GetBoundable().Bounds;
                if (bounds.Width <= 0 || bounds.Height <= 0) 
                {
                    if (this.GetCallback != null) return GetCallback().GetBrush(renderingElement, renderer, opacity, forStroke);
                    return null;
                }

                using (var transform = EffectiveGradientTransform)
                {
                    var midPoint = new PointF((points[0].X + points[1].X) / 2, (points[0].Y + points[1].Y) / 2);
                    transform.Translate(bounds.X, bounds.Y, MatrixOrder.Prepend);
                    if (this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox)
                    {
                        // Transform a normal (i.e. perpendicular line) according to the transform
                        transform.Scale(bounds.Width, bounds.Height, MatrixOrder.Prepend);
                        transform.RotateAt(-90.0f, midPoint, MatrixOrder.Prepend);
                    }
                    transform.TransformPoints(points);
                }

                if (this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox)
                {
                    // Transform the normal line back to a line such that the gradient still starts in the correct corners, but
                    // has the proper normal vector based on the transforms.  If you work out the geometry, these formulas should work.
                    var midPoint = new PointF((points[0].X + points[1].X) / 2, (points[0].Y + points[1].Y) / 2);
                    var dy = (points[1].Y - points[0].Y);
                    var dx = (points[1].X - points[0].X);
                    var x2 = points[0].X;
                    var y2 = points[1].Y;

                    if (Math.Round(dx, 4) == 0)
                    {
                        points[0] = new PointF(midPoint.X + dy / 2 * bounds.Width / bounds.Height, midPoint.Y);
                        points[1] = new PointF(midPoint.X - dy / 2 * bounds.Width / bounds.Height, midPoint.Y);
                    }
                    else if (Math.Round(dy, 4) == 0)
                    {
                        points[0] = new PointF(midPoint.X, midPoint.Y - dx / 2 * bounds.Height / bounds.Width);
                        points[1] = new PointF(midPoint.X, midPoint.Y + dx / 2 * bounds.Height / bounds.Width); ;
                    }
                    else
                    {
                        var startX = (float)((dy * dx * (midPoint.Y - y2) + Math.Pow(dx, 2) * midPoint.X + Math.Pow(dy, 2) * x2) /
                        (Math.Pow(dx, 2) + Math.Pow(dy, 2)));
                        var startY = dy * (startX - x2) / dx + y2;
                        points[0] = new PointF(startX, startY);
                        points[1] = new PointF(midPoint.X + (midPoint.X - startX), midPoint.Y + (midPoint.Y - startY));
                    }
                }
James Welle's avatar
James Welle committed
153

Eric Domke's avatar
Eric Domke committed
154
155
                var effectiveStart = points[0];
                var effectiveEnd = points[1];
James Welle's avatar
James Welle committed
156

Eric Domke's avatar
Eric Domke committed
157
                if (PointsToMove(renderingElement, points[0], points[1]) > LinePoints.None)
158
                {
Eric Domke's avatar
Eric Domke committed
159
                    var expansion = ExpandGradient(renderingElement, points[0], points[1]);
160
161
162
                    effectiveStart = expansion.StartPoint;
                    effectiveEnd = expansion.EndPoint;
                }
James Welle's avatar
James Welle committed
163

Eric Domke's avatar
Eric Domke committed
164
                var result = new LinearGradientBrush(effectiveStart, effectiveEnd, System.Drawing.Color.Transparent, System.Drawing.Color.Transparent)
165
                {
Eric Domke's avatar
Eric Domke committed
166
                    InterpolationColors = CalculateColorBlend(renderer, opacity, points[0], effectiveStart, points[1], effectiveEnd),
167
168
                    WrapMode = WrapMode.TileFlipX
                };
Eric Domke's avatar
Eric Domke committed
169
                return result;
170
171
            }
            finally
James Welle's avatar
James Welle committed
172
            {
173
174
                if (this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox) renderer.PopBoundable();
            }
James Welle's avatar
James Welle committed
175
176
        }

Eric Domke's avatar
Eric Domke committed
177
        private SvgUnit NormalizeUnit(SvgUnit orig)
James Welle's avatar
James Welle committed
178
        {
Eric Domke's avatar
Eric Domke committed
179
180
181
            return (orig.Type == SvgUnitType.Percentage && this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox ?
                    new SvgUnit(SvgUnitType.User, orig.Value / 100) :
                    orig);
davescriven's avatar
davescriven committed
182
183
        }

Eric Domke's avatar
Eric Domke committed
184
185
        [Flags]
        private enum LinePoints
davescriven's avatar
davescriven committed
186
        {
Eric Domke's avatar
Eric Domke committed
187
188
189
            None = 0,
            Start = 1,
            End = 2
davescriven's avatar
davescriven committed
190
191
        }

Eric Domke's avatar
Eric Domke committed
192
        private LinePoints PointsToMove(ISvgBoundable boundable, PointF specifiedStart, PointF specifiedEnd)
davescriven's avatar
davescriven committed
193
        {
Eric Domke's avatar
Eric Domke committed
194
195
196
197
198
199
200
201
202
203
204
205
206
            var bounds = boundable.Bounds;
            if (specifiedStart.X == specifiedEnd.X)
            {
                return (bounds.Top < specifiedStart.Y && specifiedStart.Y < bounds.Bottom ? LinePoints.Start : LinePoints.None) |
                       (bounds.Top < specifiedEnd.Y && specifiedEnd.Y < bounds.Bottom ? LinePoints.End : LinePoints.None);
            }
            else if (specifiedStart.Y == specifiedEnd.Y)
            {
                return (bounds.Left < specifiedStart.X && specifiedStart.X < bounds.Right ? LinePoints.Start : LinePoints.None) |
                       (bounds.Left < specifiedEnd.X && specifiedEnd.X < bounds.Right ? LinePoints.End : LinePoints.None);
            }
            return (boundable.Bounds.Contains(specifiedStart) ? LinePoints.Start : LinePoints.None) |
                   (boundable.Bounds.Contains(specifiedEnd) ? LinePoints.End : LinePoints.None);
davescriven's avatar
davescriven committed
207
208
        }

209
210
211
212
213
214
        public struct GradientPoints
        {
            public PointF StartPoint;
            public PointF EndPoint;

            public GradientPoints(PointF startPoint, PointF endPoint)
215
            {
216
217
218
219
220
221
                this.StartPoint = startPoint;
                this.EndPoint = endPoint;
            }
        }

        private GradientPoints ExpandGradient(ISvgBoundable boundable, PointF specifiedStart, PointF specifiedEnd)
davescriven's avatar
davescriven committed
222
        {
Eric Domke's avatar
Eric Domke committed
223
224
            var pointsToMove = PointsToMove(boundable, specifiedStart, specifiedEnd);
            if (pointsToMove == LinePoints.None)
225
            {
James Welle's avatar
James Welle committed
226
                Debug.Fail("Unexpectedly expanding gradient when not needed!");
227
                return new GradientPoints(specifiedStart, specifiedEnd);
228
            }
davescriven's avatar
davescriven committed
229

Eric Domke's avatar
Eric Domke committed
230
            var bounds = boundable.Bounds;
James Welle's avatar
James Welle committed
231
232
            var effectiveStart = specifiedStart;
            var effectiveEnd = specifiedEnd;
Eric Domke's avatar
Eric Domke committed
233
            var intersectionPoints = CandidateIntersections(bounds, specifiedStart, specifiedEnd);
James Welle's avatar
James Welle committed
234

Eric Domke's avatar
Eric Domke committed
235
            Debug.Assert(intersectionPoints.Count == 2, "Unanticipated number of intersection points");
James Welle's avatar
James Welle committed
236

Eric Domke's avatar
Eric Domke committed
237
238
239
240
241
            if (!(Math.Sign(intersectionPoints[1].X - intersectionPoints[0].X) == Math.Sign(specifiedEnd.X - specifiedStart.X) &&
                  Math.Sign(intersectionPoints[1].Y - intersectionPoints[0].Y) == Math.Sign(specifiedEnd.Y - specifiedStart.Y)))
            {
                intersectionPoints = intersectionPoints.Reverse().ToList();
            }
James Welle's avatar
James Welle committed
242

Eric Domke's avatar
Eric Domke committed
243
244
            if ((pointsToMove & LinePoints.Start) > 0) effectiveStart = intersectionPoints[0];
            if ((pointsToMove & LinePoints.End) > 0) effectiveEnd = intersectionPoints[1];
davescriven's avatar
davescriven committed
245

Eric Domke's avatar
Eric Domke committed
246
            switch (SpreadMethod)
davescriven's avatar
davescriven committed
247
            {
Eric Domke's avatar
Eric Domke committed
248
249
250
251
252
253
254
255
256
257
258
                case SvgGradientSpreadMethod.Reflect:
                case SvgGradientSpreadMethod.Repeat:
                    var specifiedLength = CalculateDistance(specifiedStart, specifiedEnd);
                    var specifiedUnitVector = new PointF((specifiedEnd.X - specifiedStart.X) / (float)specifiedLength, (specifiedEnd.Y - specifiedStart.Y) / (float)specifiedLength);
                    var oppUnitVector = new PointF(-specifiedUnitVector.X, -specifiedUnitVector.Y);

                    var startExtend = (float)(Math.Ceiling(CalculateDistance(effectiveStart, specifiedStart) / specifiedLength) * specifiedLength);
                    effectiveStart = MovePointAlongVector(specifiedStart, oppUnitVector, startExtend);
                    var endExtend = (float)(Math.Ceiling(CalculateDistance(effectiveEnd, specifiedEnd) / specifiedLength) * specifiedLength);
                    effectiveEnd = MovePointAlongVector(specifiedEnd, specifiedUnitVector, endExtend);
                    break;
James Welle's avatar
James Welle committed
259
260
            }

Eric Domke's avatar
Eric Domke committed
261
262
            return new GradientPoints(effectiveStart, effectiveEnd);
        }
James Welle's avatar
James Welle committed
263

Eric Domke's avatar
Eric Domke 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
299
300
301
302
        private IList<PointF> CandidateIntersections(RectangleF bounds, PointF p1, PointF p2)
        {
            var results = new List<PointF>();
            if (Math.Round(Math.Abs(p1.Y - p2.Y), 4) == 0)
            {
                results.Add(new PointF(bounds.Left, p1.Y));
                results.Add(new PointF(bounds.Right, p1.Y));
            }
            else if (Math.Round(Math.Abs(p1.X - p2.X), 4) == 0)
            {
                results.Add(new PointF(p1.X, bounds.Top));
                results.Add(new PointF(p1.X, bounds.Bottom));
            }
            else
            {
                PointF candidate;
                // Save some effort and duplication in the trivial case
                if ((p1.X == bounds.Left || p1.X == bounds.Right) && (p1.Y == bounds.Top || p1.Y == bounds.Bottom))
                {
                    results.Add(p1);
                }
                else
                {
                    candidate = new PointF(bounds.Left, (p2.Y - p1.Y) / (p2.X - p1.X) * (bounds.Left - p1.X) + p1.Y);
                    if (bounds.Top <= candidate.Y && candidate.Y <= bounds.Bottom) results.Add(candidate);
                    candidate = new PointF(bounds.Right, (p2.Y - p1.Y) / (p2.X - p1.X) * (bounds.Right - p1.X) + p1.Y);
                    if (bounds.Top <= candidate.Y && candidate.Y <= bounds.Bottom) results.Add(candidate);
                }
                if ((p2.X == bounds.Left || p2.X == bounds.Right) && (p2.Y == bounds.Top || p2.Y == bounds.Bottom))
                {
                    results.Add(p2);
                }
                else
                {
                    candidate = new PointF((bounds.Top - p1.Y) / (p2.Y - p1.Y) * (p2.X - p1.X) + p1.X, bounds.Top);
                    if (bounds.Left <= candidate.X && candidate.X <= bounds.Right) results.Add(candidate);
                    candidate = new PointF((bounds.Bottom - p1.Y) / (p2.Y - p1.Y) * (p2.X - p1.X) + p1.X, bounds.Bottom);
                    if (bounds.Left <= candidate.X && candidate.X <= bounds.Right) results.Add(candidate);
                }
James Welle's avatar
James Welle committed
303
304
            }

Eric Domke's avatar
Eric Domke committed
305
            return results;
James Welle's avatar
James Welle committed
306
307
        }

Eric Domke's avatar
Eric Domke committed
308
        private ColorBlend CalculateColorBlend(ISvgRenderer renderer, float opacity, PointF specifiedStart, PointF effectiveStart, PointF specifiedEnd, PointF effectiveEnd)
James Welle's avatar
James Welle committed
309
        {
Eric Domke's avatar
Eric Domke committed
310
311
312
313
314
            float startExtend;
            float endExtend;
            List<Color> colors;
            List<float> positions;
            
315
            var colorBlend = GetColorBlend(renderer, opacity, false);
James Welle's avatar
James Welle committed
316
317
318
319
320
321
322
323
324
325
326
327
328
329

            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);

Eric Domke's avatar
Eric Domke committed
330
            switch (SpreadMethod)
James Welle's avatar
James Welle committed
331
            {
Eric Domke's avatar
Eric Domke committed
332
333
334
335
336
                case SvgGradientSpreadMethod.Reflect:
                    startExtend = (float)(Math.Ceiling(CalculateDistance(effectiveStart, specifiedStart) / specifiedLength));
                    endExtend = (float)(Math.Ceiling(CalculateDistance(effectiveEnd, specifiedEnd) / specifiedLength));
                    colors = colorBlend.Colors.ToList();
                    positions = (from p in colorBlend.Positions select p + startExtend).ToList();
davescriven's avatar
davescriven committed
337

Eric Domke's avatar
Eric Domke committed
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
                    for (var i = 0; i < startExtend; i++)
                    {
                        if (i % 2 == 0)
                        {
                            for (var j = 1; j < colorBlend.Positions.Length; j++)
                            {
                                positions.Insert(0, (float)((startExtend - 1 - i) + 1 - colorBlend.Positions[j]));
                                colors.Insert(0, colorBlend.Colors[j]);
                            }
                        }
                        else
                        {
                            for (var j = 0; j < colorBlend.Positions.Length - 1; j++)
                            {
                                positions.Insert(j, (float)((startExtend - 1 - i) + colorBlend.Positions[j]));
                                colors.Insert(j, colorBlend.Colors[j]);
                            }
                        }
                    }
James Welle's avatar
James Welle committed
357

Eric Domke's avatar
Eric Domke committed
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
                    int insertPos;
                    for (var i = 0; i < endExtend; i++)
                    {
                        if (i % 2 == 0)
                        {
                            insertPos = positions.Count;
                            for (var j = 0; j < colorBlend.Positions.Length - 1; j++)
                            {
                                positions.Insert(insertPos, (float)((startExtend + 1 + i) + 1 - colorBlend.Positions[j]));
                                colors.Insert(insertPos, colorBlend.Colors[j]);
                            }
                        }
                        else
                        {
                            for (var j = 1; j < colorBlend.Positions.Length; j++)
                            {
                                positions.Add((float)((startExtend + 1 + i) + colorBlend.Positions[j]));
                                colors.Add(colorBlend.Colors[j]);
                            }
                        }
                    }
James Welle's avatar
James Welle committed
379

Eric Domke's avatar
Eric Domke committed
380
381
382
383
384
385
386
387
                    colorBlend.Colors = colors.ToArray();
                    colorBlend.Positions = (from p in positions select p / (startExtend + 1 + endExtend)).ToArray();
                    break;
                case SvgGradientSpreadMethod.Repeat:
                    startExtend = (float)(Math.Ceiling(CalculateDistance(effectiveStart, specifiedStart) / specifiedLength));
                    endExtend = (float)(Math.Ceiling(CalculateDistance(effectiveEnd, specifiedEnd) / specifiedLength));
                    colors = new List<Color>();
                    positions = new List<float>();
James Welle's avatar
James Welle committed
388

Eric Domke's avatar
Eric Domke committed
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
                    for (int i = 0; i < startExtend + endExtend + 1; i++)
                    {
                        for (int j = 0; j < colorBlend.Positions.Length; j++)
                        {
                            positions.Add((i + colorBlend.Positions[j] * 0.9999f) / (startExtend + endExtend + 1));
                            colors.Add(colorBlend.Colors[j]);
                        }
                    }
                    positions[positions.Count - 1] = 1.0f;

                    colorBlend.Colors = colors.ToArray();
                    colorBlend.Positions = positions.ToArray();

                    break;
                default:
                    for (var i = 0; i < colorBlend.Positions.Length; i++)
                    {
                        var originalPoint = MovePointAlongVector(specifiedStart, specifiedUnitVector, (float)specifiedLength * colorBlend.Positions[i]);

                        var distanceFromEffectiveStart = CalculateDistance(effectiveStart, originalPoint);

                        colorBlend.Positions[i] = (float)Math.Round(Math.Max(0F, Math.Min((distanceFromEffectiveStart / effectiveLength), 1.0F)), 5);
                    }

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

                    if (endDelta > 0)
                    {
                        colorBlend.Positions = colorBlend.Positions.Concat(new[] { 1F }).ToArray();
                        colorBlend.Colors = colorBlend.Colors.Concat(new[] { colorBlend.Colors.Last() }).ToArray();
                    }
                    break;
davescriven's avatar
davescriven committed
425
426
            }

James Welle's avatar
James Welle committed
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
            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
455
456

        }
457

James Welle's avatar
James Welle committed
458
459
460
461
462
463
464
465
466
467
        private sealed class LineF
        {
            private float X1
            {
                get;
                set;
            }

            private float Y1
            {
468
                get;
James Welle's avatar
James Welle committed
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
                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
504
            /// <remarks>http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=geometry2</remarks>
James Welle's avatar
James Welle committed
505
506
            private PointF? Intersection(LineF other)
            {
Eric Domke's avatar
Eric Domke committed
507
                const int precision = 8;
James Welle's avatar
James Welle committed
508

Eric Domke's avatar
Eric Domke committed
509
510
511
                var a1 = (double)Y2 - Y1;
                var b1 = (double)X1 - X2;
                var c1 = a1 * X1 + b1 * Y1;
James Welle's avatar
James Welle committed
512

Eric Domke's avatar
Eric Domke committed
513
514
515
516
517
518
                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
519
520
521
                {
                    return null;
                }
Eric Domke's avatar
Eric Domke committed
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
                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
543
544
545
546
547
548
549
550
551
552
553
554
            }

            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
555
556
    }
}