forked from SixLabors/ImageSharp.Drawing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDrawingCanvas{TPixel}.cs
More file actions
1676 lines (1459 loc) · 62.2 KB
/
Copy pathDrawingCanvas{TPixel}.cs
File metadata and controls
1676 lines (1459 loc) · 62.2 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
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Numerics;
using SixLabors.Fonts;
using SixLabors.Fonts.Rendering;
using SixLabors.ImageSharp.Drawing.Processing.Backends;
using SixLabors.ImageSharp.Drawing.Processing.Processors.Text;
using SixLabors.ImageSharp.Drawing.Text;
using SixLabors.ImageSharp.Memory;
using SixLabors.ImageSharp.Processing.Processors.Transforms;
namespace SixLabors.ImageSharp.Drawing.Processing;
/// <summary>
/// A drawing canvas over a frame target.
/// </summary>
/// <typeparam name="TPixel">The pixel format.</typeparam>
public sealed class DrawingCanvas<TPixel> : DrawingCanvas
where TPixel : unmanaged, IPixel<TPixel>
{
/// <summary>
/// Processing configuration used by operations executed through this canvas.
/// </summary>
private readonly Configuration configuration;
/// <summary>
/// Backend responsible for rasterizing and composing draw commands.
/// </summary>
private readonly IDrawingBackend backend;
/// <summary>
/// Destination frame receiving rendered output.
/// </summary>
private readonly ICanvasFrame<TPixel> targetFrame;
/// <summary>
/// Command batcher used to defer and submit composition commands.
/// </summary>
private readonly DrawingCanvasBatcher<TPixel> batcher;
/// <summary>
/// Temporary image resources that must stay alive until queued commands are flushed.
/// </summary>
private readonly List<Image<TPixel>> pendingImageResources = [];
/// <summary>
/// Indicates whether this canvas owns final disposal of the shared batcher.
/// </summary>
private readonly bool ownsBatcher;
/// <summary>
/// Tracks whether this instance has already been disposed.
/// </summary>
private bool isDisposed;
/// <summary>
/// Stack of saved drawing states for Save/Restore operations.
/// </summary>
private readonly Stack<DrawingCanvasState> savedStates = new();
// Per-canvas glyph-outline cache: hoists RichTextGlyphRenderer's per-glyph outline cache from
// per-DrawText-call scope up to the whole canvas, so a glyph outline built once is reused by
// every DrawText call on this canvas (across a frame's many text runs) instead of being
// rebuilt for every run on a text-heavy page.
private readonly Dictionary<RichTextGlyphRenderer.CacheKey, List<RichTextGlyphRenderer.GlyphRenderData>> glyphCache = [];
/// <summary>
/// Initializes a new instance of the <see cref="DrawingCanvas{TPixel}"/> class.
/// </summary>
/// <param name="configuration">The active processing configuration.</param>
/// <param name="options">Initial drawing options for this canvas instance.</param>
/// <param name="targetRegion">The destination target region.</param>
/// <param name="clipPaths">Initial clip paths for this canvas instance.</param>
public DrawingCanvas(
Configuration configuration,
DrawingOptions options,
Buffer2DRegion<TPixel> targetRegion,
params IPath[] clipPaths)
: this(configuration, options, new MemoryCanvasFrame<TPixel>(targetRegion), clipPaths)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DrawingCanvas{TPixel}"/> class.
/// </summary>
/// <param name="configuration">The active processing configuration.</param>
/// <param name="options">Initial drawing options for this canvas instance.</param>
/// <param name="targetFrame">The destination frame.</param>
/// <param name="clipPaths">Initial clip paths for this canvas instance.</param>
public DrawingCanvas(
Configuration configuration,
DrawingOptions options,
ICanvasFrame<TPixel> targetFrame,
params IPath[] clipPaths)
: this(configuration, options, configuration.GetDrawingBackend(), targetFrame, clipPaths)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DrawingCanvas{TPixel}"/> class with an explicit backend and initial state.
/// </summary>
/// <param name="configuration">The active processing configuration.</param>
/// <param name="options">Initial drawing options for this canvas instance.</param>
/// <param name="backend">The drawing backend implementation.</param>
/// <param name="targetFrame">The destination frame.</param>
/// <param name="clipPaths">Initial clip paths for this canvas instance.</param>
public DrawingCanvas(
Configuration configuration,
DrawingOptions options,
IDrawingBackend backend,
ICanvasFrame<TPixel> targetFrame,
params IPath[] clipPaths)
: this(
configuration,
backend,
targetFrame,
new DrawingCanvasBatcher<TPixel>(configuration),
new DrawingCanvasState(options, clipPaths, targetFrame.Bounds, targetFrame.Bounds.Location),
true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DrawingCanvas{TPixel}"/> class
/// with explicit backend and batcher instances.
/// </summary>
/// <param name="configuration">The active processing configuration.</param>
/// <param name="backend">The drawing backend implementation.</param>
/// <param name="targetFrame">The destination frame.</param>
/// <param name="batcher">The command batcher used for deferred composition.</param>
/// <param name="defaultState">The default state used when no scoped state is active.</param>
/// <param name="ownsBatcher">Whether this canvas owns final disposal of the shared batcher.</param>
private DrawingCanvas(
Configuration configuration,
IDrawingBackend backend,
ICanvasFrame<TPixel> targetFrame,
DrawingCanvasBatcher<TPixel> batcher,
DrawingCanvasState defaultState,
bool ownsBatcher)
{
Guard.NotNull(configuration, nameof(configuration));
Guard.NotNull(backend, nameof(backend));
Guard.NotNull(targetFrame, nameof(targetFrame));
Guard.NotNull(batcher, nameof(batcher));
Guard.NotNull(defaultState, nameof(defaultState));
if (!targetFrame.TryGetCpuRegion(out _) && !targetFrame.TryGetNativeSurface(out _))
{
throw new NotSupportedException("Canvas frame must expose either a CPU region or a native surface.");
}
this.configuration = configuration;
this.backend = backend;
this.targetFrame = targetFrame;
this.batcher = batcher;
this.ownsBatcher = ownsBatcher;
// Canvas coordinates are local to the current frame; origin stays at (0,0).
this.Bounds = new Rectangle(0, 0, targetFrame.Bounds.Width, targetFrame.Bounds.Height);
this.savedStates.Push(defaultState);
}
/// <inheritdoc />
public override Rectangle Bounds { get; }
/// <inheritdoc />
public override int SaveCount => this.savedStates.Count;
/// <inheritdoc />
public override int Save()
{
this.EnsureNotDisposed();
DrawingCanvasState current = this.ResolveState();
// Push a non-layer copy of the current state.
// Only states pushed by SaveLayer() should trigger layer compositing on restore.
this.savedStates.Push(new DrawingCanvasState(current.Options, current.ClipPaths, current.TargetBounds, current.DestinationOffset));
return this.savedStates.Count;
}
/// <inheritdoc />
public override int Save(DrawingOptions options, params IPath[] clipPaths)
=> this.SaveCore(options, clipPaths);
private int SaveCore(DrawingOptions options, IReadOnlyList<IPath> clipPaths)
{
this.EnsureNotDisposed();
Guard.NotNull(options, nameof(options));
Guard.NotNull(clipPaths, nameof(clipPaths));
_ = this.Save();
DrawingCanvasState current = this.ResolveState();
DrawingCanvasState state = new(options, clipPaths, current.TargetBounds, current.DestinationOffset);
_ = this.savedStates.Pop();
this.savedStates.Push(state);
return this.savedStates.Count;
}
/// <inheritdoc />
public override int SaveLayer(GraphicsOptions layerOptions, Rectangle bounds)
{
this.EnsureNotDisposed();
Guard.NotNull(layerOptions, nameof(layerOptions));
Guard.MustBeGreaterThan(bounds.Width, 0, nameof(bounds));
Guard.MustBeGreaterThan(bounds.Height, 0, nameof(bounds));
DrawingCanvasState currentState = this.ResolveState();
Rectangle absoluteLayerBounds = ResolveLayerBounds(currentState, bounds);
// Keep layer boundaries in the shared command stream so the backend can lower them inline.
this.batcher.AddComposition(CompositionCommand.CreateBeginLayer(absoluteLayerBounds, layerOptions));
// A bounded layer clips and allocates the isolated target, but it does not shift the canvas coordinate system.
DrawingCanvasState layerState = new(currentState.Options, currentState.ClipPaths, absoluteLayerBounds, currentState.DestinationOffset)
{
IsLayer = true,
LayerOptions = layerOptions,
};
this.savedStates.Push(layerState);
return this.savedStates.Count;
}
/// <inheritdoc />
public override void Restore()
{
this.EnsureNotDisposed();
if (this.savedStates.Count <= 1)
{
return;
}
DrawingCanvasState popped = this.savedStates.Pop();
if (popped.IsLayer)
{
this.batcher.AddComposition(CompositionCommand.CreateEndLayer(popped.TargetBounds, popped.LayerOptions!));
}
}
/// <inheritdoc />
public override void RestoreTo(int saveCount)
{
this.EnsureNotDisposed();
Guard.MustBeBetweenOrEqualTo(saveCount, 1, this.savedStates.Count, nameof(saveCount));
this.RestoreToCore(saveCount);
}
/// <inheritdoc cref="DrawingCanvas.CreateRegion(Rectangle)" />
public override DrawingCanvas<TPixel> CreateRegion(Rectangle region)
{
this.EnsureNotDisposed();
Rectangle clipped = Rectangle.Intersect(this.Bounds, region);
CanvasRegionFrame<TPixel> childFrame = new(this.targetFrame, clipped);
DrawingCanvasState currentState = this.ResolveState();
// Regions share the same batcher and deferred image resources. Only the root canvas owns flushing.
return new DrawingCanvas<TPixel>(
this.configuration,
this.backend,
childFrame,
this.batcher,
new DrawingCanvasState(currentState.Options, currentState.ClipPaths, childFrame.Bounds, childFrame.Bounds.Location)
{
IsLayer = currentState.IsLayer,
LayerOptions = currentState.LayerOptions,
},
false);
}
/// <inheritdoc />
public override void Clear(Brush brush, IPath path)
{
DrawingCanvasState state = this.ResolveState();
DrawingOptions options = state.Options.CloneForClearOperation();
this.ExecuteWithTemporaryState(options, state.ClipPaths, () => this.Fill(brush, path));
}
/// <inheritdoc />
public override void Fill(Brush brush, IPath path)
{
this.EnsureNotDisposed();
Guard.NotNull(path, nameof(path));
Guard.NotNull(brush, nameof(brush));
this.EnqueueFillPath(brush, path);
}
/// <inheritdoc />
public override void Apply(Rectangle region, Action<IImageProcessingContext> operation)
=> this.Apply(new RectanglePolygon(region), operation);
/// <inheritdoc />
public override void Apply(PathBuilder pathBuilder, Action<IImageProcessingContext> operation)
{
Guard.NotNull(pathBuilder, nameof(pathBuilder));
this.Apply(pathBuilder.Build(), operation);
}
/// <inheritdoc />
public override void Apply(IPath path, Action<IImageProcessingContext> operation)
{
this.EnsureNotDisposed();
Guard.NotNull(path, nameof(path));
Guard.NotNull(operation, nameof(operation));
DrawingCanvasState state = this.ResolveState();
ApplyBarrier barrier = new(
path.AsClosedPath(),
state.Options,
state.ClipPaths,
this.Bounds,
state.TargetBounds,
state.DestinationOffset,
state.IsLayer,
operation);
this.batcher.AddApplyBarrier(barrier);
}
/// <summary>
/// Draws a two-point line segment using the provided pen and drawing options.
/// </summary>
/// <param name="pen">Pen used to generate the line outline.</param>
/// <param name="start">Line start point.</param>
/// <param name="end">Line end point.</param>
public void DrawLine(Pen pen, PointF start, PointF end)
{
this.EnsureNotDisposed();
Guard.NotNull(pen, nameof(pen));
DrawingCanvasState state = this.ResolveState();
DrawingOptions effectiveOptions = state.Options;
// Stroke geometry can self-overlap; non-zero winding preserves stroke semantics.
if (effectiveOptions.ShapeOptions.IntersectionRule != IntersectionRule.NonZero)
{
ShapeOptions shapeOptions = effectiveOptions.ShapeOptions.DeepClone();
shapeOptions.IntersectionRule = IntersectionRule.NonZero;
effectiveOptions = new DrawingOptions(effectiveOptions.GraphicsOptions, shapeOptions, effectiveOptions.Transform);
}
if (state.ClipPaths.Count > 0 || !pen.StrokePattern.IsEmpty)
{
this.PrepareCompositionCore(
new Path([start, end]),
pen.StrokeFill,
effectiveOptions,
RasterizerSamplingOrigin.PixelCenter,
state.ClipPaths,
pen);
return;
}
this.PrepareStrokeLineSegmentCompositionCore(start, end, pen.StrokeFill, effectiveOptions, pen);
}
/// <inheritdoc />
public override void DrawLine(Pen pen, params PointF[] points)
{
Guard.NotNull(points, nameof(points));
if (points.Length == 2)
{
this.DrawLine(pen, points[0], points[1]);
return;
}
this.EnsureNotDisposed();
Guard.NotNull(pen, nameof(pen));
DrawingCanvasState state = this.ResolveState();
DrawingOptions effectiveOptions = state.Options;
// Stroke geometry can self-overlap; non-zero winding preserves stroke semantics.
if (effectiveOptions.ShapeOptions.IntersectionRule != IntersectionRule.NonZero)
{
ShapeOptions shapeOptions = effectiveOptions.ShapeOptions.DeepClone();
shapeOptions.IntersectionRule = IntersectionRule.NonZero;
effectiveOptions = new DrawingOptions(effectiveOptions.GraphicsOptions, shapeOptions, effectiveOptions.Transform);
}
if (state.ClipPaths.Count > 0 || !pen.StrokePattern.IsEmpty)
{
this.PrepareCompositionCore(
new Path(points),
pen.StrokeFill,
effectiveOptions,
RasterizerSamplingOrigin.PixelCenter,
state.ClipPaths,
pen);
return;
}
this.PrepareStrokePolylineCompositionCore(points, pen.StrokeFill, effectiveOptions, pen);
}
/// <inheritdoc />
public override void Draw(Pen pen, IPath path)
{
this.EnsureNotDisposed();
Guard.NotNull(pen, nameof(pen));
Guard.NotNull(path, nameof(path));
DrawingCanvasState state = this.ResolveState();
DrawingOptions effectiveOptions = state.Options;
// Stroke geometry can self-overlap; non-zero winding preserves stroke semantics.
if (effectiveOptions.ShapeOptions.IntersectionRule != IntersectionRule.NonZero)
{
ShapeOptions shapeOptions = effectiveOptions.ShapeOptions.DeepClone();
shapeOptions.IntersectionRule = IntersectionRule.NonZero;
effectiveOptions = new DrawingOptions(effectiveOptions.GraphicsOptions, shapeOptions, effectiveOptions.Transform);
}
this.PrepareCompositionCore(
path,
pen.StrokeFill,
effectiveOptions,
RasterizerSamplingOrigin.PixelCenter,
state.ClipPaths,
pen);
}
/// <inheritdoc />
public override void DrawText(
RichTextOptions textOptions,
ReadOnlySpan<char> text,
Brush? brush,
Pen? pen)
=> this.DrawTextCore(textOptions, text, path: null, brush, pen);
/// <inheritdoc />
public override void DrawText(
RichTextOptions textOptions,
ReadOnlySpan<char> text,
IPath path,
Brush? brush,
Pen? pen)
{
Guard.NotNull(path, nameof(path));
this.DrawTextCore(textOptions, text, path, brush, pen);
}
private void DrawTextCore(
RichTextOptions textOptions,
ReadOnlySpan<char> text,
IPath? path,
Brush? brush,
Pen? pen)
{
this.EnsureNotDisposed();
if (text.IsEmpty)
{
return;
}
DrawingCanvasState state = this.ResolveState();
DrawingOptions effectiveOptions = state.Options;
EnsureTextPaint(brush, pen);
RichTextOptions configuredOptions = ConfigureTextOptions(textOptions, path, out IPath? configuredPath);
using RichTextGlyphRenderer glyphRenderer = new(effectiveOptions, configuredPath, pen, brush, this.glyphCache);
TextRenderer renderer = new(glyphRenderer);
renderer.RenderText(text, configuredOptions);
this.DrawTextOperations(glyphRenderer.DrawingOperations, effectiveOptions, state.ClipPaths);
}
/// <inheritdoc />
public override void DrawText(
TextBlock textBlock,
PointF location,
float wrappingLength,
Brush? brush,
Pen? pen)
{
this.EnsureNotDisposed();
Guard.NotNull(textBlock, nameof(textBlock));
EnsureTextPaint(brush, pen);
DrawingCanvasState state = this.ResolveState();
DrawingOptions effectiveOptions = state.Options;
// Prepared text already owns shaping and layout options. The caller-supplied
// location is therefore applied as canvas placement before the active canvas
// transform, instead of mutating text options or rebuilding the block.
DrawingOptions placedOptions = new(
effectiveOptions.GraphicsOptions,
effectiveOptions.ShapeOptions,
Matrix4x4.CreateTranslation(location.X, location.Y, 0) * effectiveOptions.Transform);
using RichTextGlyphRenderer glyphRenderer = new(placedOptions, path: null, pen, brush, this.glyphCache);
textBlock.RenderTo(glyphRenderer, wrappingLength);
this.DrawTextOperations(glyphRenderer.DrawingOperations, placedOptions, state.ClipPaths);
}
/// <inheritdoc />
public override void DrawText(
TextBlock textBlock,
IPath path,
float wrappingLength,
Brush? brush,
Pen? pen)
{
this.EnsureNotDisposed();
Guard.NotNull(textBlock, nameof(textBlock));
Guard.NotNull(path, nameof(path));
EnsureTextPaint(brush, pen);
DrawingCanvasState state = this.ResolveState();
DrawingOptions effectiveOptions = state.Options;
using RichTextGlyphRenderer glyphRenderer = new(effectiveOptions, path, pen, brush, this.glyphCache);
textBlock.RenderTo(glyphRenderer, wrappingLength);
this.DrawTextOperations(glyphRenderer.DrawingOperations, effectiveOptions, state.ClipPaths);
}
/// <inheritdoc />
public override void DrawText(
LineLayout lineLayout,
PointF location,
Brush? brush,
Pen? pen)
{
this.EnsureNotDisposed();
Guard.NotNull(lineLayout, nameof(lineLayout));
EnsureTextPaint(brush, pen);
DrawingCanvasState state = this.ResolveState();
DrawingOptions effectiveOptions = state.Options;
// LineLayout represents a single already-broken line. Placement belongs
// to the drawing host, so the line can be reused in arbitrary slots
// without changing the prepared text object.
DrawingOptions placedOptions = new(
effectiveOptions.GraphicsOptions,
effectiveOptions.ShapeOptions,
Matrix4x4.CreateTranslation(location.X, location.Y, 0) * effectiveOptions.Transform);
using RichTextGlyphRenderer glyphRenderer = new(placedOptions, path: null, pen, brush, this.glyphCache);
lineLayout.RenderTo(glyphRenderer);
this.DrawTextOperations(glyphRenderer.DrawingOperations, placedOptions, state.ClipPaths);
}
/// <inheritdoc />
public override void DrawText(
LineLayout lineLayout,
IPath path,
Brush? brush,
Pen? pen)
{
this.EnsureNotDisposed();
Guard.NotNull(lineLayout, nameof(lineLayout));
Guard.NotNull(path, nameof(path));
EnsureTextPaint(brush, pen);
DrawingCanvasState state = this.ResolveState();
DrawingOptions effectiveOptions = state.Options;
using RichTextGlyphRenderer glyphRenderer = new(effectiveOptions, path, pen, brush, this.glyphCache);
lineLayout.RenderTo(glyphRenderer);
this.DrawTextOperations(glyphRenderer.DrawingOperations, effectiveOptions, state.ClipPaths);
}
/// <inheritdoc />
public override void DrawGlyphs(
Brush brush,
Pen pen,
IEnumerable<GlyphPathCollection> glyphs)
{
this.EnsureNotDisposed();
Guard.NotNull(brush, nameof(brush));
Guard.NotNull(pen, nameof(pen));
Guard.NotNull(glyphs, nameof(glyphs));
DrawingCanvasState state = this.ResolveState();
DrawingOptions baseOptions = state.Options;
IReadOnlyList<IPath> clipPaths = state.ClipPaths;
foreach (GlyphPathCollection glyph in glyphs)
{
if (glyph.LayerCount == 0)
{
continue;
}
if (glyph.LayerCount == 1)
{
this.Fill(brush, glyph.Paths);
continue;
}
float glyphArea = glyph.Bounds.Width * glyph.Bounds.Height;
for (int layerIndex = 0; layerIndex < glyph.LayerCount; layerIndex++)
{
GlyphLayerInfo layer = glyph.Layers[layerIndex];
if (layer.Count == 0)
{
continue;
}
PathCollection layerPaths = glyph.GetLayerPaths(layerIndex);
DrawingOptions layerOptions = baseOptions.CloneOrReturnForRules(
layer.IntersectionRule,
layer.PixelAlphaCompositionMode,
layer.PixelColorBlendingMode);
bool shouldFill;
if (layer.Kind is GlyphLayerKind.Decoration or GlyphLayerKind.Glyph)
{
shouldFill = true;
}
else
{
float layerArea = layerPaths.ComputeArea();
shouldFill = layerArea > 0F && glyphArea > 0F && (layerArea / glyphArea) < 0.50F;
}
this.ExecuteWithTemporaryState(layerOptions, clipPaths, () =>
{
if (shouldFill)
{
this.Fill(brush, layerPaths);
}
else
{
this.Draw(pen, layerPaths);
}
});
}
}
}
/// <inheritdoc />
public override TextMetrics MeasureText(RichTextOptions textOptions, ReadOnlySpan<char> text)
{
this.EnsureNotDisposed();
return TextMeasurer.Measure(text, textOptions);
}
/// <inheritdoc />
public override void DrawImage(
Image image,
Rectangle sourceRect,
RectangleF destinationRect,
IResampler? sampler)
{
this.EnsureNotDisposed();
Guard.NotNull(image, nameof(image));
if (image is Image<TPixel> specificImage)
{
this.DrawImageCore(specificImage, sourceRect, destinationRect, sampler, ownsSourceImage: false);
return;
}
// Only the pixels inside the clipped source region are ever sampled by the draw operation.
// When that region covers just part of the image, crop it in the source pixel format first so
// the per-pixel format conversion runs over the required region instead of the whole image.
if (!TryGetDrawImageClip(sourceRect, destinationRect, image.Bounds, out Rectangle clippedSourceRect, out RectangleF clippedDestinationRect))
{
return;
}
if (clippedSourceRect == image.Bounds)
{
Image<TPixel> convertedImage = image.CloneAs<TPixel>();
this.DrawImageCore(convertedImage, sourceRect, destinationRect, sampler, ownsSourceImage: true);
return;
}
using Image croppedSource = image.Clone(ctx => ctx.Crop(clippedSourceRect));
Image<TPixel> convertedRegion = croppedSource.CloneAs<TPixel>();
this.DrawImageCore(convertedRegion, convertedRegion.Bounds, clippedDestinationRect, sampler, ownsSourceImage: true);
}
/// <inheritdoc cref="DrawingCanvas.DrawImage(Image, Rectangle, RectangleF, IResampler?)" />
public void DrawImage(
Image<TPixel> image,
Rectangle sourceRect,
RectangleF destinationRect,
IResampler? sampler = null)
{
this.EnsureNotDisposed();
Guard.NotNull(image, nameof(image));
this.DrawImageCore(image, sourceRect, destinationRect, sampler, ownsSourceImage: false);
}
/// <inheritdoc />
public override DrawingBackendScene CreateScene()
{
this.EnsureNotDisposed();
IDisposable[]? ownedResources = this.DetachPendingImageResources();
try
{
return this.batcher.CreateScene(this.backend, this.targetFrame.Bounds, ownedResources);
}
catch
{
DisposeOwnedResources(ownedResources);
throw;
}
finally
{
this.batcher.ClearCommandBatch();
}
}
/// <inheritdoc />
public override void RenderScene(DrawingBackendScene scene)
{
this.EnsureNotDisposed();
Guard.NotNull(scene, nameof(scene));
this.batcher.AddScene(scene);
}
private void DrawImageCore(
Image<TPixel> image,
Rectangle sourceRect,
RectangleF destinationRect,
IResampler? sampler,
bool ownsSourceImage)
{
bool disposeSourceImage = ownsSourceImage;
DrawingCanvasState state = this.ResolveState();
DrawingOptions effectiveOptions = state.Options;
DrawingOptions commandOptions = effectiveOptions;
IReadOnlyList<IPath> commandClipPaths = state.ClipPaths;
Image<TPixel>? ownedImage = null;
try
{
if (!TryGetDrawImageClip(sourceRect, destinationRect, image.Bounds, out Rectangle clippedSourceRect, out RectangleF clippedDestinationRect))
{
return;
}
Size scaledSize = new(
Math.Max(1, (int)MathF.Ceiling(clippedDestinationRect.Width)),
Math.Max(1, (int)MathF.Ceiling(clippedDestinationRect.Height)));
bool requiresScaling =
clippedSourceRect.Width != scaledSize.Width ||
clippedSourceRect.Height != scaledSize.Height;
Image<TPixel> brushImage = image;
RectangleF brushImageRegion = clippedSourceRect;
RectangleF renderDestinationRect = clippedDestinationRect;
// Phase 1: Prepare source pixels (crop/scale) in image-local space.
if (requiresScaling)
{
ownedImage = CreateScaledDrawImage(image, clippedSourceRect, scaledSize, sampler);
brushImage = ownedImage;
brushImageRegion = ownedImage.Bounds;
}
else if (clippedSourceRect != image.Bounds)
{
ownedImage = image.Clone(ctx => ctx.Crop(clippedSourceRect));
brushImage = ownedImage;
brushImageRegion = ownedImage.Bounds;
}
// Phase 2: Apply canvas transform to image content when requested.
if (effectiveOptions.Transform != Matrix4x4.Identity)
{
Image<TPixel> transformed = CreateTransformedDrawImage(
brushImage,
clippedDestinationRect,
effectiveOptions.Transform,
sampler,
out renderDestinationRect);
ownedImage?.Dispose();
ownedImage = transformed;
brushImage = transformed;
brushImageRegion = transformed.Bounds;
// The image pixels and destination rect are already in transformed canvas space,
// so the queued fill must not apply the canvas transform a second time.
commandOptions = new DrawingOptions(
effectiveOptions.GraphicsOptions,
effectiveOptions.ShapeOptions,
Matrix4x4.Identity);
commandClipPaths = TransformClipPaths(state.ClipPaths, effectiveOptions.Transform);
}
if (renderDestinationRect.Width <= 0 || renderDestinationRect.Height <= 0)
{
return;
}
// Phase 3: Transfer temp-image ownership to deferred batch execution.
if (!ReferenceEquals(brushImage, image))
{
if (disposeSourceImage)
{
image.Dispose();
disposeSourceImage = false;
}
this.pendingImageResources.Add(brushImage);
ownedImage = null;
}
else if (disposeSourceImage)
{
this.pendingImageResources.Add(image);
disposeSourceImage = false;
}
ImageBrush<TPixel> brush = new(brushImage, brushImageRegion);
IPath destinationPath = new RectanglePolygon(
renderDestinationRect.X,
renderDestinationRect.Y,
renderDestinationRect.Width,
renderDestinationRect.Height);
this.PrepareCompositionCore(
destinationPath,
brush,
commandOptions,
RasterizerSamplingOrigin.PixelBoundary,
commandClipPaths);
}
finally
{
ownedImage?.Dispose();
if (disposeSourceImage)
{
image.Dispose();
}
}
}
/// <summary>
/// Prepares a path fill composition command and enqueues it in the batcher.
/// </summary>
/// <param name="path">Path to fill.</param>
/// <param name="brush">Brush used for shading.</param>
/// <param name="options">Effective drawing options.</param>
/// <param name="samplingOrigin">Rasterizer sampling origin.</param>
/// <param name="clipPaths">Optional clip paths to apply during preparation.</param>
/// <param name="pen">Optional pen for stroke commands.</param>
private void PrepareCompositionCore(
IPath path,
Brush brush,
DrawingOptions options,
RasterizerSamplingOrigin samplingOrigin,
IReadOnlyList<IPath>? clipPaths = null,
Pen? pen = null)
{
brush = this.NormalizeBrush(brush);
GraphicsOptions graphicsOptions = options.GraphicsOptions;
ShapeOptions shapeOptions = options.ShapeOptions;
RasterizationMode rasterizationMode = graphicsOptions.Antialias ? RasterizationMode.Antialiased : RasterizationMode.Aliased;
RectangleF bounds = path.Bounds;
if (samplingOrigin == RasterizerSamplingOrigin.PixelCenter)
{
bounds = new RectangleF(bounds.X + 0.5F, bounds.Y + 0.5F, bounds.Width, bounds.Height);
}
Rectangle interest = Rectangle.FromLTRB(
(int)MathF.Floor(bounds.Left),
(int)MathF.Floor(bounds.Top),
(int)MathF.Ceiling(bounds.Right),
(int)MathF.Ceiling(bounds.Bottom));
RasterizerOptions rasterizerOptions = new(
interest,
shapeOptions.IntersectionRule,
rasterizationMode,
samplingOrigin,
graphicsOptions.AntialiasThreshold);
DrawingCanvasState state = this.ResolveState();
// Commands carry their absolute target bounds and destination origin explicitly.
// Bounded layers can clip the target while preserving the active canvas coordinate origin.
if (pen is null)
{
this.batcher.AddComposition(
CompositionCommand.Create(
path,
brush,
options,
in rasterizerOptions,
state.TargetBounds,
state.DestinationOffset,
clipPaths,
state.IsLayer));
return;
}
this.batcher.AddStrokePath(
new StrokePathCommand(
path,
brush,
options,
in rasterizerOptions,
state.TargetBounds,
state.DestinationOffset,
pen,
clipPaths,
state.IsLayer));
}
/// <summary>
/// Enqueues one explicit two-point stroke line-segment command using the current canvas state.
/// </summary>
private void PrepareStrokeLineSegmentCompositionCore(
PointF start,
PointF end,
Brush brush,
DrawingOptions options,
Pen pen)
{
brush = this.NormalizeBrush(brush);
GraphicsOptions graphicsOptions = options.GraphicsOptions;
RasterizationMode rasterizationMode = graphicsOptions.Antialias ? RasterizationMode.Antialiased : RasterizationMode.Aliased;
RectangleF bounds = StrokeLineSegmentCommand.GetConservativeBounds(start, end, pen);
Rectangle interest = Rectangle.FromLTRB(
(int)MathF.Floor(bounds.Left),
(int)MathF.Floor(bounds.Top),
(int)MathF.Ceiling(bounds.Right) + 1,
(int)MathF.Ceiling(bounds.Bottom) + 1);
RasterizerOptions rasterizerOptions = new(
interest,
options.ShapeOptions.IntersectionRule,
rasterizationMode,
RasterizerSamplingOrigin.PixelCenter,
graphicsOptions.AntialiasThreshold);
DrawingCanvasState state = this.ResolveState();
this.batcher.AddStrokeLineSegment(
new StrokeLineSegmentCommand(
start,
end,
brush,
options,
in rasterizerOptions,
state.TargetBounds,
state.DestinationOffset,
pen,
state.IsLayer));
}
/// <summary>
/// Enqueues one explicit stroked open polyline command using the current canvas state.
/// </summary>
private void PrepareStrokePolylineCompositionCore(
PointF[] points,
Brush brush,
DrawingOptions options,
Pen pen)
{
brush = this.NormalizeBrush(brush);
GraphicsOptions graphicsOptions = options.GraphicsOptions;
RasterizationMode rasterizationMode = graphicsOptions.Antialias ? RasterizationMode.Antialiased : RasterizationMode.Aliased;
RectangleF bounds = StrokePolylineCommand.GetConservativeBounds(points, pen);
Rectangle interest = Rectangle.FromLTRB(
(int)MathF.Floor(bounds.Left),
(int)MathF.Floor(bounds.Top),
(int)MathF.Ceiling(bounds.Right) + 1,
(int)MathF.Ceiling(bounds.Bottom) + 1);
RasterizerOptions rasterizerOptions = new(
interest,
options.ShapeOptions.IntersectionRule,
rasterizationMode,
RasterizerSamplingOrigin.PixelCenter,
graphicsOptions.AntialiasThreshold);
DrawingCanvasState state = this.ResolveState();
this.batcher.AddStrokePolyline(
new StrokePolylineCommand(
points,
brush,
options,
in rasterizerOptions,
state.TargetBounds,
state.DestinationOffset,
pen,
state.IsLayer));
}