-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCanvasRenderContext.cs
1187 lines (1044 loc) · 44.8 KB
/
CanvasRenderContext.cs
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 file="CanvasRenderContext.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Implements <see cref="IRenderContext" /> for <see cref="System.Windows.Controls.Canvas" />.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot.Dark.Wpf
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using FontWeights = OxyPlot.FontWeights;
using HorizontalAlignment = OxyPlot.HorizontalAlignment;
using Path = System.Windows.Shapes.Path;
using VerticalAlignment = OxyPlot.VerticalAlignment;
/// <summary>
/// Implements <see cref="IRenderContext" /> for <see cref="System.Windows.Controls.Canvas" />.
/// </summary>
public class CanvasRenderContext : IRenderContext
{
/// <summary>
/// The maximum number of figures per geometry.
/// </summary>
private const int MaxFiguresPerGeometry = 16;
/// <summary>
/// The maximum number of polylines per line.
/// </summary>
private const int MaxPolylinesPerLine = 64;
/// <summary>
/// The minimum number of points per polyline.
/// </summary>
private const int MinPointsPerPolyline = 16;
/// <summary>
/// The images in use
/// </summary>
private readonly HashSet<OxyImage> imagesInUse = new HashSet<OxyImage>();
/// <summary>
/// The image cache
/// </summary>
private readonly Dictionary<OxyImage, BitmapSource> imageCache = new Dictionary<OxyImage, BitmapSource>();
/// <summary>
/// The brush cache.
/// </summary>
private readonly Dictionary<OxyColor, Brush> brushCache = new Dictionary<OxyColor, Brush>();
/// <summary>
/// The font family cache
/// </summary>
private readonly Dictionary<string, FontFamily> fontFamilyCache = new Dictionary<string, FontFamily>();
/// <summary>
/// The canvas.
/// </summary>
private readonly Canvas canvas;
/// <summary>
/// The clip rectangle.
/// </summary>
private Rect? clip;
/// <summary>
/// The current tool tip
/// </summary>
private string currentToolTip;
/// <summary>
/// The pixel scale
/// </summary>
private double pixelScale;
/// <summary>
/// Initializes a new instance of the <see cref="CanvasRenderContext" /> class.
/// </summary>
/// <param name="canvas">The canvas.</param>
public CanvasRenderContext(Canvas canvas)
{
this.canvas = canvas;
this.TextFormattingMode = TextFormattingMode.Display;
this.TextMeasurementMethod = TextMeasurementMethod.TextBlock;
this.UseStreamGeometry = true;
this.RendersToScreen = true;
this.BalancedLineDrawingThicknessLimit = 3.5;
// TODO: issue 10221 - try to find the size of physical pixels
var presentationSource = PresentationSource.FromVisual(canvas);
if (presentationSource != null && presentationSource.CompositionTarget != null)
{
this.pixelScale = presentationSource.CompositionTarget.TransformToDevice.M11;
}
else
{
this.pixelScale = 1;
}
}
/// <summary>
/// Gets or sets the text measurement method.
/// </summary>
/// <value>The text measurement method.</value>
public TextMeasurementMethod TextMeasurementMethod { get; set; }
/// <summary>
/// Gets or sets the text formatting mode.
/// </summary>
/// <value>The text formatting mode. The default value is <see cref="System.Windows.Media.TextFormattingMode.Display"/>.</value>
public TextFormattingMode TextFormattingMode { get; set; }
/// <summary>
/// Gets or sets the thickness limit for "balanced" line drawing.
/// </summary>
public double BalancedLineDrawingThicknessLimit { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use stream geometry for lines and polygons rendering.
/// </summary>
/// <value><c>true</c> if stream geometry should be used; otherwise, <c>false</c> .</value>
/// <remarks>The XamlWriter does not serialize StreamGeometry, so set this to <c>false</c> if you want to export to XAML. Using stream geometry seems to be slightly faster than using path geometry.</remarks>
public bool UseStreamGeometry { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the context renders to screen.
/// </summary>
/// <value><c>true</c> if the context renders to screen; otherwise, <c>false</c>.</value>
public bool RendersToScreen { get; set; }
/// <summary>
/// Draws an ellipse.
/// </summary>
/// <param name="rect">The rectangle.</param>
/// <param name="fill">The fill color. If set to <c>OxyColors.Undefined</c>, the ellipse will not be filled.</param>
/// <param name="stroke">The stroke color. If set to <c>OxyColors.Undefined</c>, the ellipse will not be stroked.</param>
/// <param name="thickness">The thickness (in device independent units, 1/96 inch).</param>
public void DrawEllipse(OxyRect rect, OxyColor fill, OxyColor stroke, double thickness)
{
var e = this.CreateAndAdd<Ellipse>(rect.Left, rect.Top);
this.SetStroke(e, stroke, thickness);
if (fill.IsVisible())
{
e.Fill = this.GetCachedBrush(fill);
}
e.Width = rect.Width;
e.Height = rect.Height;
Canvas.SetLeft(e, rect.Left);
Canvas.SetTop(e, rect.Top);
}
/// <summary>
/// Draws a collection of ellipses, where all have the same stroke and fill.
/// This performs better than calling DrawEllipse multiple times.
/// </summary>
/// <param name="rectangles">The rectangles.</param>
/// <param name="fill">The fill color. If set to <c>OxyColors.Undefined</c>, the ellipses will not be filled.</param>
/// <param name="stroke">The stroke color. If set to <c>OxyColors.Undefined</c>, the ellipses will not be stroked.</param>
/// <param name="thickness">The stroke thickness (in device independent units, 1/96 inch).</param>
public void DrawEllipses(IList<OxyRect> rectangles, OxyColor fill, OxyColor stroke, double thickness)
{
var path = this.CreateAndAdd<Path>();
this.SetStroke(path, stroke, thickness);
if (!fill.IsUndefined())
{
path.Fill = this.GetCachedBrush(fill);
}
var gg = new GeometryGroup { FillRule = FillRule.Nonzero };
foreach (var rect in rectangles)
{
gg.Children.Add(new EllipseGeometry(this.ToRect(rect)));
}
path.Data = gg;
}
/// <summary>
/// Draws a polyline.
/// </summary>
/// <param name="points">The points.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness (in device independent units, 1/96 inch).</param>
/// <param name="dashArray">The dash array (in device independent units, 1/96 inch). Use <c>null</c> to get a solid line.</param>
/// <param name="lineJoin">The line join type.</param>
/// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param>
public void DrawLine(
IList<ScreenPoint> points,
OxyColor stroke,
double thickness,
double[] dashArray,
LineJoin lineJoin,
bool aliased)
{
if (thickness < this.BalancedLineDrawingThicknessLimit)
{
this.DrawLineBalanced(points, stroke, thickness, dashArray, lineJoin, aliased);
return;
}
var e = this.CreateAndAdd<Polyline>();
this.SetStroke(e, stroke, thickness, lineJoin, dashArray, 0, aliased);
e.Points = this.ToPointCollection(points, aliased);
}
/// <summary>
/// Draws line segments defined by points (0,1) (2,3) (4,5) etc.
/// This should have better performance than calling DrawLine for each segment.
/// </summary>
/// <param name="points">The points.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness (in device independent units, 1/96 inch).</param>
/// <param name="dashArray">The dash array (in device independent units, 1/96 inch).</param>
/// <param name="lineJoin">The line join type.</param>
/// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param>
public void DrawLineSegments(
IList<ScreenPoint> points,
OxyColor stroke,
double thickness,
double[] dashArray,
LineJoin lineJoin,
bool aliased)
{
if (this.UseStreamGeometry)
{
this.DrawLineSegmentsByStreamGeometry(points, stroke, thickness, dashArray, lineJoin, aliased);
return;
}
Path path = null;
PathGeometry pathGeometry = null;
int count = 0;
for (int i = 0; i + 1 < points.Count; i += 2)
{
if (path == null)
{
path = this.CreateAndAdd<Path>();
this.SetStroke(path, stroke, thickness, lineJoin, dashArray, 0, aliased);
pathGeometry = new PathGeometry();
}
var figure = new PathFigure { StartPoint = this.ToPoint(points[i], aliased), IsClosed = false };
figure.Segments.Add(new LineSegment(this.ToPoint(points[i + 1], aliased), true) { IsSmoothJoin = false });
pathGeometry.Figures.Add(figure);
count++;
// Must limit the number of figures, otherwise drawing errors...
if (count > MaxFiguresPerGeometry || dashArray != null)
{
path.Data = pathGeometry;
path = null;
count = 0;
}
}
if (path != null)
{
path.Data = pathGeometry;
}
}
/// <summary>
/// Draws a polygon.
/// </summary>
/// <param name="points">The points.</param>
/// <param name="fill">The fill color. If set to <c>OxyColors.Undefined</c>, the polygon will not be filled.</param>
/// <param name="stroke">The stroke color. If set to <c>OxyColors.Undefined</c>, the polygon will not be stroked.</param>
/// <param name="thickness">The stroke thickness (in device independent units, 1/96 inch).</param>
/// <param name="dashArray">The dash array (in device independent units, 1/96 inch).</param>
/// <param name="lineJoin">The line join type.</param>
/// <param name="aliased">If set to <c>true</c> the polygon will be aliased.</param>
public void DrawPolygon(
IList<ScreenPoint> points,
OxyColor fill,
OxyColor stroke,
double thickness,
double[] dashArray,
LineJoin lineJoin,
bool aliased)
{
var e = this.CreateAndAdd<Polygon>();
this.SetStroke(e, stroke, thickness, lineJoin, dashArray, 0, aliased);
if (!fill.IsUndefined())
{
e.Fill = this.GetCachedBrush(fill);
}
e.Points = this.ToPointCollection(points, aliased);
}
/// <summary>
/// Draws a collection of polygons, where all polygons have the same stroke and fill.
/// This performs better than calling DrawPolygon multiple times.
/// </summary>
/// <param name="polygons">The polygons.</param>
/// <param name="fill">The fill color. If set to <c>OxyColors.Undefined</c>, the polygons will not be filled.</param>
/// <param name="stroke">The stroke color. If set to <c>OxyColors.Undefined</c>, the polygons will not be stroked.</param>
/// <param name="thickness">The stroke thickness (in device independent units, 1/96 inch).</param>
/// <param name="dashArray">The dash array (in device independent units, 1/96 inch).</param>
/// <param name="lineJoin">The line join type.</param>
/// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param>
public void DrawPolygons(
IList<IList<ScreenPoint>> polygons,
OxyColor fill,
OxyColor stroke,
double thickness,
double[] dashArray,
LineJoin lineJoin,
bool aliased)
{
var usg = this.UseStreamGeometry;
Path path = null;
StreamGeometry streamGeometry = null;
StreamGeometryContext sgc = null;
PathGeometry pathGeometry = null;
int count = 0;
foreach (var polygon in polygons)
{
if (path == null)
{
path = this.CreateAndAdd<Path>();
this.SetStroke(path, stroke, thickness, lineJoin, dashArray, 0, aliased);
if (!fill.IsUndefined())
{
path.Fill = this.GetCachedBrush(fill);
}
if (usg)
{
streamGeometry = new StreamGeometry { FillRule = FillRule.Nonzero };
sgc = streamGeometry.Open();
}
else
{
pathGeometry = new PathGeometry { FillRule = FillRule.Nonzero };
}
}
PathFigure figure = null;
bool first = true;
foreach (var p in polygon)
{
var point = aliased ? this.ToPixelAlignedPoint(p) : this.ToPoint(p);
if (first)
{
if (usg)
{
sgc.BeginFigure(point, !fill.IsUndefined(), true);
}
else
{
figure = new PathFigure
{
StartPoint = point,
IsFilled = !fill.IsUndefined(),
IsClosed = true
};
pathGeometry.Figures.Add(figure);
}
first = false;
}
else
{
if (usg)
{
sgc.LineTo(point, !stroke.IsUndefined(), true);
}
else
{
figure.Segments.Add(new LineSegment(point, !stroke.IsUndefined()) { IsSmoothJoin = true });
}
}
}
count++;
// Must limit the number of figures, otherwise drawing errors...
if (count > MaxFiguresPerGeometry)
{
if (usg)
{
sgc.Close();
path.Data = streamGeometry;
}
else
{
path.Data = pathGeometry;
}
path = null;
count = 0;
}
}
if (path != null)
{
if (usg)
{
sgc.Close();
path.Data = streamGeometry;
}
else
{
path.Data = pathGeometry;
}
}
}
/// <summary>
/// Draws a rectangle.
/// </summary>
/// <param name="rect">The rectangle.</param>
/// <param name="fill">The fill color. If set to <c>OxyColors.Undefined</c>, the rectangle will not be filled.</param>
/// <param name="stroke">The stroke color. If set to <c>OxyColors.Undefined</c>, the rectangle will not be stroked.</param>
/// <param name="thickness">The stroke thickness (in device independent units, 1/96 inch).</param>
public void DrawRectangle(OxyRect rect, OxyColor fill, OxyColor stroke, double thickness)
{
var e = this.CreateAndAdd<Rectangle>(rect.Left, rect.Top);
this.SetStroke(e, stroke, thickness, LineJoin.Miter, null, 0, true);
if (!fill.IsUndefined())
{
e.Fill = this.GetCachedBrush(fill);
}
e.Width = rect.Width;
e.Height = rect.Height;
Canvas.SetLeft(e, rect.Left);
Canvas.SetTop(e, rect.Top);
}
/// <summary>
/// Draws a collection of rectangles, where all have the same stroke and fill.
/// This performs better than calling DrawRectangle multiple times.
/// </summary>
/// <param name="rectangles">The rectangles.</param>
/// <param name="fill">The fill color. If set to <c>OxyColors.Undefined</c>, the rectangles will not be filled.</param>
/// <param name="stroke">The stroke color. If set to <c>OxyColors.Undefined</c>, the rectangles will not be stroked.</param>
/// <param name="thickness">The stroke thickness (in device independent units, 1/96 inch).</param>
public void DrawRectangles(IList<OxyRect> rectangles, OxyColor fill, OxyColor stroke, double thickness)
{
var path = this.CreateAndAdd<Path>();
this.SetStroke(path, stroke, thickness);
if (!fill.IsUndefined())
{
path.Fill = this.GetCachedBrush(fill);
}
var gg = new GeometryGroup { FillRule = FillRule.Nonzero };
foreach (var rect in rectangles)
{
gg.Children.Add(new RectangleGeometry { Rect = this.ToPixelAlignedRect(rect) });
}
path.Data = gg;
}
/// <summary>
/// Draws text.
/// </summary>
/// <param name="p">The position.</param>
/// <param name="text">The text.</param>
/// <param name="fill">The text color.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">Size of the font (in device independent units, 1/96 inch).</param>
/// <param name="fontWeight">The font weight.</param>
/// <param name="rotate">The rotation angle.</param>
/// <param name="halign">The horizontal alignment.</param>
/// <param name="valign">The vertical alignment.</param>
/// <param name="maxSize">The maximum size of the text (in device independent units, 1/96 inch).</param>
public void DrawText(
ScreenPoint p,
string text,
OxyColor fill,
string fontFamily,
double fontSize,
double fontWeight,
double rotate,
HorizontalAlignment halign,
VerticalAlignment valign,
OxySize? maxSize)
{
var tb = this.CreateAndAdd<TextBlock>();
tb.Text = text;
tb.Foreground = this.GetCachedBrush(fill);
if (fontFamily != null)
{
tb.FontFamily = this.GetCachedFontFamily(fontFamily);
}
if (fontSize > 0)
{
tb.FontSize = fontSize;
}
if (fontWeight > 0)
{
tb.FontWeight = GetFontWeight(fontWeight);
}
TextOptions.SetTextFormattingMode(tb, this.TextFormattingMode);
double dx = 0;
double dy = 0;
if (maxSize != null || halign != HorizontalAlignment.Left || valign != VerticalAlignment.Top)
{
tb.Measure(new Size(1000, 1000));
var size = tb.DesiredSize;
if (maxSize != null)
{
if (size.Width > maxSize.Value.Width + 1e-3)
{
size.Width = Math.Max(maxSize.Value.Width, 0);
}
if (size.Height > maxSize.Value.Height + 1e-3)
{
size.Height = Math.Max(maxSize.Value.Height, 0);
}
tb.Width = size.Width;
tb.Height = size.Height;
}
if (halign == HorizontalAlignment.Center)
{
dx = -size.Width / 2;
}
if (halign == HorizontalAlignment.Right)
{
dx = -size.Width;
}
if (valign == VerticalAlignment.Middle)
{
dy = -size.Height / 2;
}
if (valign == VerticalAlignment.Bottom)
{
dy = -size.Height;
}
}
var transform = new TransformGroup();
transform.Children.Add(new TranslateTransform(dx, dy));
if (Math.Abs(rotate) > double.Epsilon)
{
transform.Children.Add(new RotateTransform(rotate));
}
transform.Children.Add(new TranslateTransform(p.X, p.Y));
tb.RenderTransform = transform;
if (tb.Clip != null)
{
tb.Clip.Transform = tb.RenderTransform.Inverse as Transform;
}
tb.SetValue(RenderOptions.ClearTypeHintProperty, ClearTypeHint.Enabled);
}
/// <summary>
/// Measures the size of the specified text.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">Size of the font (in device independent units, 1/96 inch).</param>
/// <param name="fontWeight">The font weight.</param>
/// <returns>
/// The size of the text (in device independent units, 1/96 inch).
/// </returns>
public OxySize MeasureText(string text, string fontFamily, double fontSize, double fontWeight)
{
if (string.IsNullOrEmpty(text))
{
return OxySize.Empty;
}
if (this.TextMeasurementMethod == TextMeasurementMethod.GlyphTypeface)
{
return this.MeasureTextByGlyphTypeface(text, fontFamily, fontSize, fontWeight);
}
var tb = new TextBlock { Text = text };
TextOptions.SetTextFormattingMode(tb, this.TextFormattingMode);
if (fontFamily != null)
{
tb.FontFamily = new FontFamily(fontFamily);
}
if (fontSize > 0)
{
tb.FontSize = fontSize;
}
if (fontWeight > 0)
{
tb.FontWeight = GetFontWeight(fontWeight);
}
tb.Measure(new Size(1000, 1000));
return new OxySize(tb.DesiredSize.Width, tb.DesiredSize.Height);
}
/// <summary>
/// Sets the tool tip for the following items.
/// </summary>
/// <param name="text">The text in the tool tip.</param>
public void SetToolTip(string text)
{
this.currentToolTip = text;
}
/// <summary>
/// Draws a portion of the specified <see cref="OxyImage" />.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="srcX">The x-coordinate of the upper-left corner of the portion of the source image to draw.</param>
/// <param name="srcY">The y-coordinate of the upper-left corner of the portion of the source image to draw.</param>
/// <param name="srcWidth">Width of the portion of the source image to draw.</param>
/// <param name="srcHeight">Height of the portion of the source image to draw.</param>
/// <param name="destX">The x-coordinate of the upper-left corner of drawn image.</param>
/// <param name="destY">The y-coordinate of the upper-left corner of drawn image.</param>
/// <param name="destWidth">The width of the drawn image.</param>
/// <param name="destHeight">The height of the drawn image.</param>
/// <param name="opacity">The opacity.</param>
/// <param name="interpolate">interpolate if set to <c>true</c>.</param>
public void DrawImage(
OxyImage source,
double srcX,
double srcY,
double srcWidth,
double srcHeight,
double destX,
double destY,
double destWidth,
double destHeight,
double opacity,
bool interpolate)
{
if (destWidth <= 0 || destHeight <= 0 || srcWidth <= 0 || srcHeight <= 0)
{
return;
}
var image = this.CreateAndAdd<Image>(destX, destY);
var bitmapChain = this.GetImageSource(source);
// ReSharper disable CompareOfFloatsByEqualityOperator
if (srcX == 0 && srcY == 0 && srcWidth == bitmapChain.PixelWidth && srcHeight == bitmapChain.PixelHeight)
// ReSharper restore CompareOfFloatsByEqualityOperator
{
// do not crop
}
else
{
bitmapChain = new CroppedBitmap(bitmapChain, new Int32Rect((int)srcX, (int)srcY, (int)srcWidth, (int)srcHeight));
}
image.Opacity = opacity;
image.Width = destWidth;
image.Height = destHeight;
image.Stretch = Stretch.Fill;
RenderOptions.SetBitmapScalingMode(image, interpolate ? BitmapScalingMode.HighQuality : BitmapScalingMode.NearestNeighbor);
// Set the position of the image
Canvas.SetLeft(image, destX);
Canvas.SetTop(image, destY);
//// alternative: image.RenderTransform = new TranslateTransform(destX, destY);
image.Source = bitmapChain;
}
/// <summary>
/// Sets the clipping rectangle.
/// </summary>
/// <param name="clippingRect">The clipping rectangle.</param>
/// <returns><c>true</c> if the clip rectangle was set.</returns>
public bool SetClip(OxyRect clippingRect)
{
this.clip = this.ToRect(clippingRect);
return true;
}
/// <summary>
/// Resets the clip rectangle.
/// </summary>
public void ResetClip()
{
this.clip = null;
}
/// <summary>
/// Cleans up resources not in use.
/// </summary>
/// <remarks>This method is called at the end of each rendering.</remarks>
public void CleanUp()
{
// Find the images in the cache that has not been used since last call to this method
var imagesToRelease = this.imageCache.Keys.Where(i => !this.imagesInUse.Contains(i)).ToList();
// Remove the images from the cache
foreach (var i in imagesToRelease)
{
this.imageCache.Remove(i);
}
this.imagesInUse.Clear();
}
/// <summary>
/// Measures the size of the specified text by a faster method (using GlyphTypefaces).
/// </summary>
/// <param name="text">The text.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">The font size.</param>
/// <param name="fontWeight">The font weight.</param>
/// <returns>The size of the text.</returns>
protected OxySize MeasureTextByGlyphTypeface(string text, string fontFamily, double fontSize, double fontWeight)
{
if (string.IsNullOrEmpty(text))
{
return OxySize.Empty;
}
var typeface = new Typeface(
new FontFamily(fontFamily), FontStyles.Normal, GetFontWeight(fontWeight), FontStretches.Normal);
GlyphTypeface glyphTypeface;
if (!typeface.TryGetGlyphTypeface(out glyphTypeface))
{
throw new InvalidOperationException("No glyph typeface found");
}
return MeasureTextSize(glyphTypeface, fontSize, text);
}
/// <summary>
/// Gets the font weight.
/// </summary>
/// <param name="fontWeight">The font weight value.</param>
/// <returns>The font weight.</returns>
private static FontWeight GetFontWeight(double fontWeight)
{
return fontWeight > FontWeights.Normal ? System.Windows.FontWeights.Bold : System.Windows.FontWeights.Normal;
}
/// <summary>
/// Fast text size calculation
/// </summary>
/// <param name="glyphTypeface">The glyph typeface.</param>
/// <param name="sizeInEm">The size.</param>
/// <param name="s">The text.</param>
/// <returns>The text size.</returns>
private static OxySize MeasureTextSize(GlyphTypeface glyphTypeface, double sizeInEm, string s)
{
double width = 0;
double lineWidth = 0;
int lines = 0;
foreach (char ch in s)
{
switch (ch)
{
case '\n':
lines++;
if (lineWidth > width)
{
width = lineWidth;
}
lineWidth = 0;
continue;
case '\t':
continue;
}
ushort glyph = glyphTypeface.CharacterToGlyphMap[ch];
double advanceWidth = glyphTypeface.AdvanceWidths[glyph];
lineWidth += advanceWidth;
}
lines++;
if (lineWidth > width)
{
width = lineWidth;
}
return new OxySize(Math.Round(width * sizeInEm, 2), Math.Round(lines * glyphTypeface.Height * sizeInEm, 2));
}
/// <summary>
/// Creates an element of the specified type and adds it to the canvas.
/// </summary>
/// <typeparam name="T">Type of element to create.</typeparam>
/// <param name="clipOffsetX">The clip offset executable.</param>
/// <param name="clipOffsetY">The clip offset asynchronous.</param>
/// <returns>The element.</returns>
private T CreateAndAdd<T>(double clipOffsetX = 0, double clipOffsetY = 0) where T : FrameworkElement, new()
{
// TODO: here we can reuse existing elements in the canvas.Children collection
var element = new T();
if (this.clip != null)
{
element.Clip = new RectangleGeometry(
new Rect(
this.clip.Value.X - clipOffsetX,
this.clip.Value.Y - clipOffsetY,
this.clip.Value.Width,
this.clip.Value.Height));
}
this.canvas.Children.Add(element);
this.ApplyToolTip(element);
return element;
}
/// <summary>
/// Applies the current tool tip to the specified element.
/// </summary>
/// <param name="element">The element.</param>
private void ApplyToolTip(FrameworkElement element)
{
if (!string.IsNullOrEmpty(this.currentToolTip))
{
element.ToolTip = this.currentToolTip;
}
}
/// <summary>
/// Draws the line segments by stream geometry.
/// </summary>
/// <param name="points">The points.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The thickness.</param>
/// <param name="dashArray">The dash array. Use <c>null</c> to get a solid line.</param>
/// <param name="lineJoin">The line join.</param>
/// <param name="aliased">Draw aliased line if set to <c>true</c> .</param>
private void DrawLineSegmentsByStreamGeometry(
IList<ScreenPoint> points,
OxyColor stroke,
double thickness,
double[] dashArray,
LineJoin lineJoin,
bool aliased)
{
StreamGeometry streamGeometry = null;
StreamGeometryContext streamGeometryContext = null;
int count = 0;
for (int i = 0; i + 1 < points.Count; i += 2)
{
if (streamGeometry == null)
{
streamGeometry = new StreamGeometry();
streamGeometryContext = streamGeometry.Open();
}
streamGeometryContext.BeginFigure(this.ToPoint(points[i], aliased), false, false);
streamGeometryContext.LineTo(this.ToPoint(points[i + 1], aliased), true, false);
count++;
// Must limit the number of figures, otherwise drawing errors...
if (count > MaxFiguresPerGeometry || dashArray != null)
{
streamGeometryContext.Close();
var path = this.CreateAndAdd<Path>();
this.SetStroke(path, stroke, thickness, lineJoin, dashArray, 0, aliased);
path.Data = streamGeometry;
streamGeometry = null;
count = 0;
}
}
if (streamGeometry != null)
{
streamGeometryContext.Close();
var path = this.CreateAndAdd<Path>();
this.SetStroke(path, stroke, thickness, lineJoin, null, 0, aliased);
path.Data = streamGeometry;
}
}
/// <summary>
/// Gets the cached brush.
/// </summary>
/// <param name="color">The color.</param>
/// <returns>The brush.</returns>
private Brush GetCachedBrush(OxyColor color)
{
if (color.A == 0)
{
return null;
}
Brush brush;
if (!this.brushCache.TryGetValue(color, out brush))
{
brush = new SolidColorBrush(color.ToColor());
brush.Freeze();
this.brushCache.Add(color, brush);
}
return brush;
}
/// <summary>
/// Gets the cached font family.
/// </summary>
/// <param name="familyName">Name of the family.</param>
/// <returns>The FontFamily.</returns>
private FontFamily GetCachedFontFamily(string familyName)
{
if (familyName == null)
{
return null;
}
FontFamily ff;
if (!this.fontFamilyCache.TryGetValue(familyName, out ff))
{
ff = new FontFamily(familyName);
this.fontFamilyCache.Add(familyName, ff);
}
return ff;
}
/// <summary>
/// Sets the stroke properties of the specified shape object.
/// </summary>
/// <param name="shape">The shape.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The thickness.</param>
/// <param name="lineJoin">The line join.</param>
/// <param name="dashArray">The dash array. Use <c>null</c> to get a solid line.</param>
/// <param name="dashOffset">The dash offset.</param>
/// <param name="aliased">The aliased.</param>
private void SetStroke(
Shape shape,
OxyColor stroke,
double thickness,
LineJoin lineJoin = LineJoin.Miter,
IEnumerable<double> dashArray = null,
double dashOffset = 0,
bool aliased = false)
{
if (!stroke.IsUndefined() && thickness > 0)
{
shape.Stroke = this.GetCachedBrush(stroke);
switch (lineJoin)
{
case LineJoin.Round:
shape.StrokeLineJoin = PenLineJoin.Round;
break;
case LineJoin.Bevel:
shape.StrokeLineJoin = PenLineJoin.Bevel;
break;
// The default StrokeLineJoin is Miter
}
if (Math.Abs(thickness - 1) > double.Epsilon)
{
// only set if different from the default value (1)
shape.StrokeThickness = thickness;
}
if (dashArray != null)
{
shape.StrokeDashArray = new DoubleCollection(dashArray);
shape.StrokeDashOffset = dashOffset;