-
Notifications
You must be signed in to change notification settings - Fork 371
Expand file tree
/
Copy pathSkSvg.cs
More file actions
1855 lines (1605 loc) · 48 KB
/
SkSvg.cs
File metadata and controls
1855 lines (1605 loc) · 48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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
205
206
207
208
209
210
211
212
213
214
215
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
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
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
425
426
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using SkiaSharp;
using System.Threading;
namespace FFImageLoading.Svg.Platform
{
[Preserve(AllMembers = true)]
public class SKSvg
{
private const float DefaultPPI = 160f;
private const bool DefaultThrowOnUnsupportedElement = false;
private static readonly IFormatProvider icult = CultureInfo.InvariantCulture;
private static readonly XNamespace xlink = "http://www.w3.org/1999/xlink";
private static readonly XNamespace svg = "http://www.w3.org/2000/svg";
private static readonly char[] WS = new char[] { ' ', '\t', '\n', '\r' };
private static readonly Regex unitRe = new Regex("px|pt|em|ex|pc|cm|mm|in");
private static readonly Regex percRe = new Regex("%");
private static readonly Regex urlRe = new Regex(@"url\s*\(\s*#([^\)]+)\)");
private static readonly Regex keyValueRe = new Regex(@"\s*([\w-]+)\s*:\s*(.*)");
private static readonly Regex WSRe = new Regex(@"\s{2,}");
private readonly Dictionary<string, string> styles = new Dictionary<string, string>();
private readonly Dictionary<string, XElement> defs = new Dictionary<string, XElement>();
private readonly Dictionary<string, SKSvgMask> masks = new Dictionary<string, SKSvgMask>();
private readonly Dictionary<string, ISKSvgFill> fillDefs = new Dictionary<string, ISKSvgFill>();
private readonly Dictionary<XElement, string> elementFills = new Dictionary<XElement, string>();
private readonly Dictionary<XElement, string> strokeElementFills = new Dictionary<XElement, string>();
private readonly XmlReaderSettings xmlReaderSettings = new XmlReaderSettings()
{
DtdProcessing = DtdProcessing.Ignore,
IgnoreComments = true,
};
public SKSvg()
: this(DefaultPPI, SKSize.Empty)
{
}
public SKSvg(float pixelsPerInch)
: this(pixelsPerInch, SKSize.Empty)
{
}
public SKSvg(SKSize canvasSize)
: this(DefaultPPI, canvasSize)
{
}
public SKSvg(float pixelsPerInch, SKSize canvasSize)
{
CanvasSize = canvasSize;
PixelsPerInch = pixelsPerInch;
ThrowOnUnsupportedElement = DefaultThrowOnUnsupportedElement;
}
public bool HasRasterImage { get; private set; }
public float PixelsPerInch { get; set; }
public bool ThrowOnUnsupportedElement { get; set; }
public SKRect ViewBox { get; private set; }
public SKSize CanvasSize { get; private set; }
public SKPicture Picture { get; private set; }
public string Description { get; private set; }
public string Title { get; private set; }
public string Version { get; private set; }
public SKPicture Load(string filename, CancellationToken token = default)
{
using (var stream = File.OpenRead(filename))
{
return Load(stream, token);
}
}
public SKPicture Load(Stream stream, CancellationToken token = default)
{
using (var reader = XmlReader.Create(stream, xmlReaderSettings, CreateSvgXmlContext()))
{
return Load(reader, token);
}
}
public SKPicture Load(XmlReader reader, CancellationToken token = default)
{
return Load(XDocument.Load(reader), token);
}
private static XmlParserContext CreateSvgXmlContext()
{
var table = new NameTable();
var manager = new XmlNamespaceManager(table);
manager.AddNamespace(string.Empty, svg.NamespaceName);
manager.AddNamespace("xlink", xlink.NamespaceName);
return new XmlParserContext(null, manager, null, XmlSpace.None);
}
private SKPicture Load(XDocument xdoc, CancellationToken token = default)
{
var svg = xdoc.Root;
var ns = svg.Name.Namespace;
// find the defs (gradients) - and follow all hrefs
foreach (var d in svg.Descendants())
{
var id = ReadId(d);
if (!string.IsNullOrEmpty(id))
defs[id] = ReadDefinition(d);
}
Version = svg.Attribute("version")?.Value;
Title = svg.Element(ns + "title")?.Value;
Description = svg.Element(ns + "desc")?.Value ?? svg.Element(ns + "description")?.Value;
// TODO: parse the "preserveAspectRatio" values properly
var preserveAspectRatio = svg.Attribute("preserveAspectRatio")?.Value;
// get the SVG dimensions
var viewBoxA = svg.Attribute("viewBox") ?? svg.Attribute("viewPort");
if (viewBoxA != null)
{
ViewBox = ReadRectangle(viewBoxA.Value);
}
if (CanvasSize.IsEmpty)
{
// get the user dimensions
var widthA = svg.Attribute("width");
var heightA = svg.Attribute("height");
var width = ReadNumber(widthA);
var height = ReadNumber(heightA);
var size = new SKSize(width, height);
if (widthA == null)
{
size.Width = ViewBox.Width;
}
else if (widthA.Value.Contains("%"))
{
size.Width *= ViewBox.Width;
}
if (heightA == null)
{
size.Height = ViewBox.Height;
}
else if (heightA != null && heightA.Value.Contains("%"))
{
size.Height *= ViewBox.Height;
}
// set the property
CanvasSize = size;
}
token.ThrowIfCancellationRequested();
// create the picture from the elements
using (var recorder = new SKPictureRecorder())
using (var canvas = recorder.BeginRecording(SKRect.Create(CanvasSize)))
{
// if there is no viewbox, then we don't do anything, otherwise
// scale the SVG dimensions to fit inside the user dimensions
if (!ViewBox.IsEmpty && (Math.Abs(ViewBox.Width - CanvasSize.Width) > float.Epsilon
|| Math.Abs(ViewBox.Height - CanvasSize.Height) > float.Epsilon))
{
if (preserveAspectRatio == "none")
{
canvas.Scale(CanvasSize.Width / ViewBox.Width, CanvasSize.Height / ViewBox.Height);
}
else
{
// TODO: just center scale for now
var scale = Math.Min(CanvasSize.Width / ViewBox.Width, CanvasSize.Height / ViewBox.Height);
var centered = SKRect.Create(CanvasSize).AspectFit(ViewBox.Size);
canvas.Translate(centered.Left, centered.Top);
canvas.Scale(scale, scale);
}
}
// translate the canvas by the viewBox origin
canvas.Translate(-ViewBox.Left, -ViewBox.Top);
// if the viewbox was specified, then crop to that
if (!ViewBox.IsEmpty)
{
canvas.ClipRect(ViewBox);
}
// read style
SKPaint stroke = null;
SKPaint fill = CreatePaint();
var style = ReadPaints(svg, ref stroke, ref fill, true);
// read elements
LoadElements(svg.Elements(), canvas, stroke, fill, token);
Picture = recorder.EndRecording();
}
return Picture;
}
private void LoadElements(IEnumerable<XElement> elements, SKCanvas canvas, SKPaint stroke, SKPaint fill, CancellationToken token = default)
{
foreach (var e in elements)
{
ReadElement(e, canvas, stroke?.Clone(), fill?.Clone());
}
}
private void ReadElement(XElement e, SKCanvas canvas, SKPaint stroke, SKPaint fill, bool isMask = false, CancellationToken token = default)
{
token.ThrowIfCancellationRequested();
if (e.Attribute("display")?.Value == "none")
return;
// SVG element
var elementName = e.Name.LocalName;
var isGroup = elementName == "g";
// read style
var style = ReadPaints(e, ref stroke, ref fill, isGroup, isMask);
if (style.TryGetValue("display", out var displayStyle) && displayStyle == "none")
return;
var xy = ReadElementXY(e);
canvas.Save();
try
{
var mask = ReadMask(style);
if (!isMask && mask != null)
{
canvas.SaveLayer(new SKPaint());
canvas.Clear();
try
{
using (var strokePaint = mask.Stroke?.Clone())
using (var fillPaint = mask.Fill?.Clone())
{
// TODO Is it Skia bug? When the same color is used for fill and mask nothing is drawn
if (strokePaint != null && strokePaint.Color == stroke?.Color)
strokePaint.Color = new SKColor((byte)~strokePaint.Color.Red, (byte)~strokePaint.Color.Green, (byte)~strokePaint.Color.Blue);
// TODO Is it Skia bug? When the same color is used for fill and mask nothing is drawn
if (fillPaint != null && fillPaint.Color == fill?.Color)
fillPaint.Color = new SKColor((byte)~fillPaint.Color.Red, (byte)~fillPaint.Color.Green, (byte)~fillPaint.Color.Blue);
foreach (var gElement in mask.Element.Elements())
{
ReadElement(gElement, canvas, strokePaint, fillPaint);
}
}
using (var strokePaint = stroke?.Clone())
using (var fillPaint = fill?.Clone())
{
if (strokePaint != null)
strokePaint.BlendMode = SKBlendMode.SrcIn;
if (fillPaint != null)
fillPaint.BlendMode = SKBlendMode.SrcIn;
ReadElement(e, canvas, strokePaint, fillPaint, true);
}
}
finally
{
canvas.Restore();
}
return;
}
if (elementName != "use")
{
// transform matrix
var transform = ReadTransform(e.Attribute("transform")?.Value ?? string.Empty, xy);
canvas.Concat(ref transform);
}
// clip-path
var clipPath = ReadClipPath(e.Attribute("clip-path")?.Value ?? string.Empty);
if (clipPath != null)
{
canvas.ClipPath(clipPath);
}
// parse elements
switch (elementName)
{
case "image":
{
var image = ReadImage(e);
if (image.Bytes != null)
{
using (var bitmap = SKBitmap.Decode(image.Bytes))
{
if (bitmap != null)
{
HasRasterImage = true;
canvas.DrawBitmap(bitmap, image.Rect);
}
}
}
}
break;
case "text":
if (stroke != null || fill != null)
{
var spans = ReadText(e, stroke?.Clone(), fill?.Clone());
if (spans.Any())
{
canvas.DrawText(spans);
}
}
break;
case "rect":
case "ellipse":
case "circle":
case "path":
case "polygon":
case "polyline":
case "line":
if (stroke != null || fill != null)
{
var elementPath = ReadElement(e, style);
if (elementPath == null)
break;
if (fill != null && elementFills.TryGetValue(e, out var fillId)
&& fillDefs.TryGetValue(fillId, out var addFill))
{
var elementSize = ReadElementSize(e);
var bounds = SKRect.Create(xy, elementSize);
addFill.ApplyFill(fill, bounds);
}
if (stroke != null && strokeElementFills.TryGetValue(e,
out var strokeFillId) && fillDefs.TryGetValue(strokeFillId, out var addStrokeFill))
{
var elementSize = ReadElementSize(e);
var bounds = SKRect.Create(xy, elementSize);
addStrokeFill.ApplyFill(stroke, bounds);
}
if (fill != null)
{
canvas.DrawPath(elementPath, fill);
}
if (stroke != null)
{
canvas.DrawPath(elementPath, stroke);
}
}
break;
case "g":
if (e.HasElements)
{
// get current group opacity
var groupOpacity = ReadOpacity(style);
try
{
if (groupOpacity != 1.0f)
{
var opacity = (byte)(255 * groupOpacity);
var opacityPaint = new SKPaint
{
Color = SKColors.Black.WithAlpha(opacity)
};
// apply the opacity
canvas.SaveLayer(opacityPaint);
}
foreach (var gElement in e.Elements())
{
ReadElement(gElement, canvas, stroke?.Clone(), fill?.Clone(), isMask);
}
}
finally
{
// restore state
if (groupOpacity != 1.0f)
canvas.Restore();
}
}
break;
case "use":
if (e.HasAttributes)
{
var href = ReadHref(e);
if (href != null)
{
if (string.Equals(href.Name.LocalName, "symbol", StringComparison.OrdinalIgnoreCase))
{
RenderSymbol(href, e, canvas, stroke?.Clone(), fill?.Clone(), e.Attributes());
}
else
{
ApplyAttributesToElement(e.Attributes(), href, new string[] { "href", "id" });
ReadElement(href, canvas, stroke?.Clone(), fill?.Clone(), isMask);
}
}
}
break;
case "switch":
if (e.HasElements)
{
foreach (var ee in e.Elements())
{
var requiredFeatures = ee.Attribute("requiredFeatures");
var requiredExtensions = ee.Attribute("requiredExtensions");
var systemLanguage = ee.Attribute("systemLanguage");
// TODO: evaluate requiredFeatures, requiredExtensions and systemLanguage
var isVisible =
requiredFeatures == null &&
requiredExtensions == null &&
systemLanguage == null;
if (isVisible)
{
ReadElement(ee, canvas, stroke?.Clone(), fill?.Clone(), isMask);
}
}
}
break;
case "mask":
if (e.HasElements)
{
masks.Add(ReadId(e), new SKSvgMask(stroke, fill, e));
}
break;
case "style":
CssHelpers.ParseSelectors(e.Value, styles);
break;
case "defs":
var styleNodes = e.Descendants();
if (styleNodes != null)
{
foreach (var item in styleNodes)
{
if (item.Name.LocalName == "style")
{
CssHelpers.ParseSelectors(item.Value, styles);
}
}
}
break;
case "a":
foreach (var child in e.Descendants())
{
ReadElement(child, canvas, stroke?.Clone(), fill?.Clone(), isMask);
}
break;
case "clipPath":
case "title":
case "desc":
case "description":
// already read earlier
break;
default:
LogOrThrow($"SVG element '{elementName}' is not supported");
break;
}
}
finally
{
// restore matrix
canvas.Restore();
}
}
private SKSvgImage ReadImage(XElement e)
{
var width = ReadNumber(e.Attribute("width"));
var height = ReadNumber(e.Attribute("height"));
var rect = SKRect.Create(width, height);
byte[] bytes = null;
var uri = ReadHrefString(e);
if (uri != null)
{
if (uri.StartsWith("data:"))
{
bytes = ReadUriBytes(uri);
}
else
{
LogOrThrow($"Remote images are not supported");
}
}
return new SKSvgImage(rect, uri, bytes);
}
private SKPath ReadElement(XElement e, Dictionary<string, string> style = null)
{
var path = new SKPath();
var elementName = e.Name.LocalName;
switch (elementName)
{
case "rect":
var rect = ReadRoundedRect(e);
if (rect.IsRounded)
path.AddRoundRect(rect.Rect, rect.RadiusX, rect.RadiusY);
else
path.AddRect(rect.Rect);
break;
case "ellipse":
var oval = ReadOval(e);
path.AddOval(oval.BoundingRect);
break;
case "circle":
var circle = ReadCircle(e);
path.AddCircle(circle.Center.X, circle.Center.Y, circle.Radius);
break;
case "path":
case "polygon":
case "polyline":
string data;
if (elementName == "path")
{
data = e.Attribute("d")?.Value;
}
else
{
data = "M" + e.Attribute("points")?.Value;
if (elementName == "polygon")
data += " Z";
}
if (!string.IsNullOrWhiteSpace(data))
{
path.Dispose();
path = SKPath.ParseSvgPathData(data);
}
path.FillType = ReadFillRule(style);
break;
case "line":
var line = ReadLine(e);
path.MoveTo(line.P1);
path.LineTo(line.P2);
break;
default:
path.Dispose();
path = null;
break;
}
return path;
}
private void RenderSymbol(XElement symbol, XElement use, SKCanvas canvas, SKPaint stroke, SKPaint fill, IEnumerable<XAttribute> attributes)
{
if (symbol == null || use == null)
return;
canvas.Save();
try
{
var point = ReadElementXY(use);
// adjust the canvas for use's location
canvas.Translate(point.X, point.Y);
var symbolViewBox = ReadElementViewBox(symbol);
var useSize = ReadElementSize(use);
var aspectRatio = symbol.Attribute("preserveAspectRatio")?.Value;
ScaleViewBoxToSize(canvas, symbolViewBox, useSize, aspectRatio);
// adjust the canvas for viewBox's origin
if (!symbolViewBox.IsEmpty)
canvas.Translate(-symbolViewBox.Left, -symbolViewBox.Top);
foreach (var ee in symbol.Elements())
{
// apply all attributes to each contained element
ApplyAttributesToElement(attributes, ee, new string[] { "href", "id", "transform" });
ReadElement(ee, canvas, stroke?.Clone(), fill?.Clone());
}
}
finally
{
canvas.Restore();
}
}
private static void ApplyAttributesToElement(IEnumerable<XAttribute> attributes, XElement e, string[] ignoreAttributes)
{
if (e == null || attributes == null)
return;
foreach (var attribute in attributes)
{
bool skipAttribute = false;
var name = attribute.Name.LocalName;
foreach (var ignoreStr in ignoreAttributes)
{
if (name.Equals(ignoreStr, StringComparison.OrdinalIgnoreCase))
{
skipAttribute = true;
break;
}
}
if (skipAttribute)
continue;
e.SetAttributeValue(attribute.Name, attribute.Value);
}
}
private void ScaleViewBoxToSize(SKCanvas canvas, SKRect viewBox, SKSize size, string aspectRatio)
{
// if the viewbox is empty, no scaling is required
if (viewBox.IsEmpty || Math.Abs(viewBox.Width) < float.Epsilon || Math.Abs(viewBox.Height) < float.Epsilon)
return;
// we only want to exit if width and height are both empty because if one is missing, the
// other will be derived using the aspec ratio
if (size.IsEmpty)
return;
// scale the viewbox to fit into the requested size
var scaleX = size.Width / viewBox.Width;
var scaleY = size.Height / viewBox.Height;
// if either height or width is zero, set the missing scale to the other dimension
if (Math.Abs(size.Width) < float.Epsilon)
scaleX = scaleY;
if (Math.Abs(size.Height) < float.Epsilon)
scaleY = scaleX;
if (!string.Equals(aspectRatio, "none", StringComparison.OrdinalIgnoreCase))
{
// if aspectRation is anything except "none", scale proportionally to the smallest dimension value
if (scaleX < scaleY)
scaleY = scaleX;
if (scaleY < scaleX)
scaleX = scaleY;
}
canvas.Scale(scaleX, scaleY);
}
private SKOval ReadOval(XElement e)
{
var cx = ReadNumber(e.Attribute("cx"));
var cy = ReadNumber(e.Attribute("cy"));
var rx = ReadNumber(e.Attribute("rx"));
var ry = ReadNumber(e.Attribute("ry"));
return new SKOval(new SKPoint(cx, cy), rx, ry);
}
private SKCircle ReadCircle(XElement e)
{
var cx = ReadNumber(e.Attribute("cx"));
var cy = ReadNumber(e.Attribute("cy"));
var rr = ReadNumber(e.Attribute("r"));
return new SKCircle(new SKPoint(cx, cy), rr);
}
private SKLine ReadLine(XElement e)
{
var x1 = ReadNumber(e.Attribute("x1"));
var x2 = ReadNumber(e.Attribute("x2"));
var y1 = ReadNumber(e.Attribute("y1"));
var y2 = ReadNumber(e.Attribute("y2"));
return new SKLine(new SKPoint(x1, y1), new SKPoint(x2, y2));
}
private SKRoundedRect ReadRoundedRect(XElement e)
{
var width = ReadNumber(e.Attribute("width"));
var height = ReadNumber(e.Attribute("height"));
var rx = ReadOptionalNumber(e.Attribute("rx"));
var ry = ReadOptionalNumber(e.Attribute("ry"));
var rect = SKRect.Create(width, height);
return new SKRoundedRect(rect, rx ?? ry ?? 0, ry ?? rx ?? 0);
}
private SKText ReadText(XElement e, SKPaint stroke, SKPaint fill)
{
var textAlign = ReadTextAlignment(e);
var baselineShift = ReadBaselineShift(e);
var style = ReadPaints(e, ref stroke, ref fill, false);
ReadFontAttributes(style, ref stroke, ref fill);
var spans = new SKText(new SKPoint(), textAlign);
// textAlign is used for all spans within the <text> element. If different textAligns would be needed, it is necessary to use
// several <text> elements instead of <tspan> elements
fill.TextAlign = SKTextAlign.Left; // fixed alignment for all spans
if (stroke != null)
stroke.TextAlign = SKTextAlign.Left; // fixed alignment for all spans
ReadTextElement(e, spans, textAlign, baselineShift, stroke, fill);
return spans;
}
private void ReadTextElement(XElement e, SKText spans, SKTextAlign textAlign, float baselineShift, SKPaint stroke, SKPaint fill)
{
var nodes = e.Nodes().ToArray();
for (int i = 0; i < nodes.Length; i++)
{
var clonedFill = fill.Clone();
var clonedStroke = stroke?.Clone();
var style = ReadPaints(e, ref clonedStroke, ref clonedFill, false);
ReadFontAttributes(style, ref clonedStroke, ref clonedFill);
var c = nodes[i];
if (c.NodeType == XmlNodeType.Text)
{
var isFirst = i == 0;
var isLast = i == nodes.Length - 1;
// TODO: check for preserve whitespace
var textSegments = ((XText)c).Value.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
var count = textSegments.Length;
if (count > 0)
{
if (isFirst)
textSegments[0] = textSegments[0].TrimStart();
if (isLast)
textSegments[count - 1] = textSegments[count - 1].TrimEnd();
var text = WSRe.Replace(string.Concat(textSegments), " ");
if (string.IsNullOrEmpty(text))
continue;
spans.Append(new SKTextSpan(text, clonedStroke, clonedFill, baselineShift: baselineShift));
}
}
else if (c is XElement ce && ce.Name.LocalName == "tspan")
{
if (ce.HasElements)
{
ReadTextElement(ce, spans, textAlign, baselineShift, stroke, clonedFill);
}
else
{
var text = ce.Value;
if (string.IsNullOrEmpty(text))
continue;
// the current span may want to change the cursor position
var x = ReadOptionalNumber(ce.Attribute("x"));
var y = ReadOptionalNumber(ce.Attribute("y"));
// Don't read text-anchor from tspans!, Only use enclosing text-anchor from text element!
baselineShift = ReadBaselineShift(ce);
spans.Append(new SKTextSpan(text, clonedStroke, clonedFill, x, y, baselineShift));
}
}
}
}
private void ReadFontAttributes(Dictionary<string, string> style, ref SKPaint stroke, ref SKPaint fill)
{
var fontFamily = fill.Typeface?.FamilyName ?? SKTypeface.Default.FamilyName;
var fontStyle = fill.Typeface?.FontSlant ?? SKFontStyleSlant.Upright;
var fontWeight = (SKFontStyleWeight?)fill.Typeface?.FontWeight ?? SKFontStyleWeight.Normal;
var fontWidth = (SKFontStyleWidth?)fill.Typeface?.FontWidth ?? SKFontStyleWidth.Normal;
if (style.TryGetValue("font-style", out var cssFontStyle))
TryParseFontStyle(cssFontStyle, out fontStyle, fontStyle);
if (style.TryGetValue("font-weight", out var cssFontWeight))
TryParseFontWeight(cssFontWeight, out fontWeight, fontWeight);
if (style.TryGetValue("font-stretch", out var cssFontStretch))
TryParseFontWidth(cssFontStretch, out fontWidth, fontWidth);
if (style.TryGetValue("font-family", out var ffamily))
fontFamily = ffamily;
var typeface = SKTypeface.FromFamilyName(fontFamily, fontWeight, fontWidth, fontStyle);
if (stroke != null)
stroke.Typeface = typeface;
fill.Typeface = typeface;
if (style.TryGetValue("font-size", out var fsize))
{
var size = ReadNumber(fsize);
if (stroke != null)
stroke.TextSize = size;
fill.TextSize = size;
}
}
private static SKPathFillType ReadFillRule(Dictionary<string, string> style, SKPathFillType defaultFillRule = SKPathFillType.Winding)
{
var fillRule = defaultFillRule;
if (style != null && style.TryGetValue("fill-rule", out var rule) && !string.IsNullOrWhiteSpace(rule))
{
switch (rule)
{
case "evenodd":
fillRule = SKPathFillType.EvenOdd;
break;
case "nonzero":
fillRule = SKPathFillType.Winding;
break;
default:
fillRule = defaultFillRule;
break;
}
}
return fillRule;
}
private static bool TryParseFontStyle(string value, out SKFontStyleSlant fontStyle, SKFontStyleSlant defaultFontStyle = SKFontStyleSlant.Upright)
{
switch (value)
{
case "italic":
fontStyle = SKFontStyleSlant.Italic;
return true;
case "oblique":
fontStyle = SKFontStyleSlant.Oblique;
return true;
case "normal":
fontStyle = SKFontStyleSlant.Upright;
return true;
default:
fontStyle = defaultFontStyle;
return false;
}
}
private bool TryParseFontWidth(string value, out SKFontStyleWidth fontStretch, SKFontStyleWidth defaultFontStretch = SKFontStyleWidth.Normal)
{
if (string.IsNullOrWhiteSpace(value))
{
fontStretch = defaultFontStretch;
return false;
}
switch (value)
{
case "ultra-condensed":
fontStretch = SKFontStyleWidth.UltraCondensed;
return true;
case "extra-condensed":
fontStretch = SKFontStyleWidth.ExtraCondensed;
return true;
case "condensed":
fontStretch = SKFontStyleWidth.Condensed;
return true;
case "semi-condensed":
fontStretch = SKFontStyleWidth.SemiCondensed;
return true;
case "normal":
fontStretch = SKFontStyleWidth.Normal;
return true;
case "semi-expanded":
fontStretch = SKFontStyleWidth.SemiExpanded;
return true;
case "expanded":
fontStretch = SKFontStyleWidth.Expanded;
return true;
case "extra-expanded":
fontStretch = SKFontStyleWidth.ExtraExpanded;
return true;
case "ultra-expanded":
fontStretch = SKFontStyleWidth.UltraExpanded;
return true;
case "wider":
fontStretch = (SKFontStyleWidth)(Math.Min(9, (int)defaultFontStretch + 1));
return true;
case "narrower":
fontStretch = (SKFontStyleWidth)(Math.Max(1, (int)defaultFontStretch - 1));
return true;
default:
fontStretch = defaultFontStretch;
return false;
}
}
private bool TryParseFontWeight(string value, out SKFontStyleWeight fontWeight, SKFontStyleWeight defaultFontWeight = SKFontStyleWeight.Normal)
{
if (string.IsNullOrWhiteSpace(value))
{
fontWeight = defaultFontWeight;
return false;
}
if (int.TryParse(value, out var number) && number >= 100 && number <= 1000)
{
fontWeight = (SKFontStyleWeight)(number / 100 * 100);
return true;
}
switch (value)
{
case "normal":
fontWeight = SKFontStyleWeight.Normal;
return true;
case "bold":
fontWeight = SKFontStyleWeight.Bold;
return true;
case "bolder":
fontWeight = (SKFontStyleWeight)Math.Min(1000, (int)defaultFontWeight + 100);
return true;
case "lighter":
fontWeight = (SKFontStyleWeight)Math.Max(100, (int)defaultFontWeight - 100);
return true;
default:
fontWeight = defaultFontWeight;
return false;
}
}
private void LogOrThrow(string message)
{
if (ThrowOnUnsupportedElement)
throw new NotSupportedException(message);
Debug.WriteLine(message);
}
private string GetString(Dictionary<string, string> style, string name, string defaultValue = "")
{
if (style != null && style.TryGetValue(name, out string v))
return v;
return defaultValue;
}
private SKSvgMask ReadMask(Dictionary<string, string> style)
{
SKSvgMask mask = null;
var maskID = GetString(style, "mask").Trim();
if (!string.IsNullOrEmpty(maskID))
{
var urlM = urlRe.Match(maskID);
if (urlM.Success)
{
var id = urlM.Groups[1].Value.Trim();
masks.TryGetValue(id, out mask);
}
}
return mask;
}
private string ReadId(XElement d)
{
return d.Attribute("id")?.Value?.Trim();
}
private Dictionary<string, string> ReadStyle(string style)
{
var d = new Dictionary<string, string>();
var kvs = style.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var kv in kvs)
{
var m = keyValueRe.Match(kv);
if (m.Success)
{
var k = m.Groups[1].Value;
var v = m.Groups[2].Value;
if (k == "font")