-
Notifications
You must be signed in to change notification settings - Fork 977
Expand file tree
/
Copy pathImageRenderContext.cs
More file actions
933 lines (799 loc) · 37.8 KB
/
Copy pathImageRenderContext.cs
File metadata and controls
933 lines (799 loc) · 37.8 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
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ImageRenderContext.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Provides an implementation of IRenderContext which draws to an ImageSharp Image.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
#nullable enable
namespace OxyPlot.ImageSharp
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using OxyPlot;
using SixLabors.ImageSharp;
using SixLabors.Fonts;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Drawing;
using SixLabors.ImageSharp.Processing.Processors;
/// <summary>
/// Provides an implementation of IRenderContext which draws to a <see cref="Image"/>.
/// </summary>
public class ImageRenderContext : ClippingRenderContext, IDisposable
{
/// <summary>
/// The default font to use when a request font cannot be found.
/// </summary>
private static readonly string FallbackFontFamily = "Arial";
/// <summary>
/// Image to which the the <see cref="ImageRenderContext"/> will render.
/// </summary>
private readonly Image<Rgba32> image;
/// <summary>
/// Image to which we will render when clipping.
/// </summary>
private readonly Image<Rgba32> clipImage;
/// <summary>
/// Whether or not the ImageRenderContext has been disposed.
/// </summary>
private bool disposedValue = false;
/// <summary>
/// The current clipping rectangle.
/// </summary>
private Rectangle clippingRectangle;
/// <summary>
/// A value indicating whether we are currently clipping.
/// </summary>
private bool clipping;
/// <summary>
/// Initializes a new instance of the <see cref="ImageRenderContext"/> class.
/// </summary>
/// <param name="width">The width of the image.</param>
/// <param name="height">The height of the image.</param>
/// <param name="background">The background color of the image.</param>
/// <param name="dpi">The number of dots per inch (DPI).</param>
public ImageRenderContext(int width, int height, OxyColor background, double dpi = 96)
{
this.image = new Image<Rgba32>(width, height);
this.clipImage = new Image<Rgba32>(width, height);
this.image.Metadata.HorizontalResolution = dpi;
this.image.Metadata.VerticalResolution = dpi;
this.clipImage.Metadata.HorizontalResolution = dpi;
this.clipImage.Metadata.VerticalResolution = dpi;
this.Dpi = (float)dpi;
this.DpiScale = (float)(dpi / 96.0);
this.image.Mutate(img => img.BackgroundColor(ToRgba32(background)));
this.RendersToScreen = false;
this.clipping = false;
}
/// <summary>
/// Gets the DPI scaling factor. A value of 1 corresponds to 96 DPI (dots per inch).
/// </summary>
private float DpiScale { get; }
/// <summary>
/// Gets the number of dots per inch (DPI).
/// </summary>
private float Dpi { get; }
/// <summary>
/// Gets the current target image.
/// </summary>
private Image Target => this.clipping ? this.clipImage : this.image;
/// <summary>
/// Gets a copy of the image.
/// </summary>
/// <returns>A copy of the internal image.</returns>
public Image GetImageCopy()
{
this.EnsureClippedRegion();
return this.image.Clone();
}
/// <summary>
/// Saves the image to the specified stream as a png.
/// </summary>
/// <param name="output">The output stream.</param>
public void SaveAsPng(Stream output)
{
this.EnsureClippedRegion();
this.image.SaveAsPng(output);
}
/// <summary>
/// Saves the image to the specified stream as a bmp.
/// </summary>
/// <param name="output">The output stream.</param>
public void SaveAsBmp(Stream output)
{
this.EnsureClippedRegion();
// TODO: investigate bmp encoder options
this.image.SaveAsBmp(output);
}
/// <summary>
/// Saves the image to the specified stream as a gif.
/// </summary>
/// <param name="output">The output stream.</param>
public void SaveAsGif(Stream output)
{
this.EnsureClippedRegion();
// TODO: investigate gif encoder options
this.image.SaveAsGif(output);
}
/// <summary>
/// Saves the image to the specified stream as a jpeg.
/// </summary>
/// <param name="output">The output stream.</param>
/// <param name="quality">The quality of the exported jpeg, a value between 0 and 100.</param>
public void SaveAsJpeg(Stream output, int quality = 75)
{
this.EnsureClippedRegion();
this.image.SaveAsJpeg(output, new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder() { Quality = quality });
}
/// <inheritdoc/>
public override void DrawText(ScreenPoint p, string text, OxyColor fill, string? fontFamily = null, double fontSize = 10, double fontWeight = 400, double rotation = 0, OxyPlot.HorizontalAlignment horizontalAlignment = OxyPlot.HorizontalAlignment.Left, OxyPlot.VerticalAlignment verticalAlignment = OxyPlot.VerticalAlignment.Top, OxySize? maxSize = null)
{
if (text == null || !fill.IsVisible())
{
return;
}
var font = this.GetFontOrThrow(fontFamily, fontSize, this.ToFontStyle(fontWeight));
var actualFontSize = this.NominalFontSizeToPoints(fontSize);
var outputX = this.Convert(p.X);
var outputY = this.Convert(p.Y);
var outputPosition = new PointF(outputX, outputY);
var cos = (float)Math.Cos(rotation * Math.PI / 180.0);
var sin = (float)Math.Sin(rotation * Math.PI / 180.0);
// measure bounds of the whole text (we only need the height)
var bounds = this.MeasureTextLoose(text, fontFamily!, fontSize, fontWeight);
var boundsHeight = this.Convert(bounds.Height);
var offsetHeight = new PointF(boundsHeight * -sin, boundsHeight * cos);
// determine the font metrids for this font size at 96 DPI
var actualDescent = this.Convert(actualFontSize * this.MilliPointsToNominalResolution(font.FontMetrics.VerticalMetrics.Descender));
var offsetDescent = new PointF(actualDescent * -sin, actualDescent * cos);
var actualLineHeight = this.Convert(actualFontSize * this.MilliPointsToNominalResolution(font.FontMetrics.VerticalMetrics.LineHeight));
var offsetLineHeight = new PointF(actualLineHeight * -sin, actualLineHeight * cos);
var actualLineGap = this.Convert(actualFontSize * this.MilliPointsToNominalResolution(font.FontMetrics.VerticalMetrics.LineGap));
var offsetLineGap = new PointF(actualLineGap * -sin, actualLineGap * cos);
// find top of the whole text
var deltaY = verticalAlignment switch
{
OxyPlot.VerticalAlignment.Top => 1.0f,
OxyPlot.VerticalAlignment.Middle => 0.5f,
OxyPlot.VerticalAlignment.Bottom => 0.0f,
_ => throw new ArgumentOutOfRangeException(nameof(verticalAlignment)),
};
// this is the top of the top line
var topPosition = outputPosition + (offsetHeight * deltaY) - offsetHeight;
// need this later
var deltaX = horizontalAlignment switch
{
OxyPlot.HorizontalAlignment.Left => -0.0f,
OxyPlot.HorizontalAlignment.Center => -0.5f,
OxyPlot.HorizontalAlignment.Right => -1.0f,
_ => throw new ArgumentOutOfRangeException(nameof(horizontalAlignment)),
};
var lines = StringHelper.SplitLines(text);
for (int li = 0; li < lines.Length; li++)
{
var line = lines[li];
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
// measure bounds of just the line (we only need the width)
var lineBounds = this.MeasureTextLoose(line, fontFamily!, fontSize, fontWeight);
var lineBoundsWidth = this.Convert(lineBounds.Width);
var offsetLineWidth = new PointF(lineBoundsWidth * cos, lineBoundsWidth * sin);
// find the left baseline position
var lineTop = topPosition + (offsetLineGap * li) + (offsetLineHeight * li);
var lineBaseLineLeft = lineTop + offsetLineWidth * deltaX + offsetLineHeight + offsetDescent;
// this seems to produce consistent and correct results, but we have to rotate it manually, so render it at the origin for simplicity
var textPath = new PathBuilder().AddLine(0f, 0f, lineBoundsWidth, 0).Build();
var glyphsAtOrigin = TextBuilder.GenerateGlyphs(line, textPath, new TextOptions(font)
{
Dpi = this.Dpi,
HorizontalAlignment = SixLabors.Fonts.HorizontalAlignment.Left,
VerticalAlignment = SixLabors.Fonts.VerticalAlignment.Bottom, // sit on the line (baseline)
KerningMode = KerningMode.Auto,
});
// translate and rotate into possition
var transform = Matrix3x2Extensions.CreateRotationDegrees((float)rotation);
transform.Translation = lineBaseLineLeft;
var glyphs = glyphsAtOrigin.Transform(transform);
// draw the glyphs
this.Target.Mutate(img =>
{
img.Fill(ToRgba32(fill), glyphs);
});
}
}
/// <inheritdoc/>
public override OxySize MeasureText(string text, string? fontFamily = null, double fontSize = 10, double fontWeight = 500)
{
return this.MeasureTextLoose(text, fontFamily!, fontSize, fontWeight);
}
/// <inheritdoc/>
public override 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 (source == null)
{
return;
}
var dest = new RectangleF((float)this.Convert(destX), (float)this.Convert(destY), (float)this.Convert(destWidth), (float)this.Convert(destHeight));
var src = new RectangleF((float)srcX, (float)srcY, (float)srcWidth, (float)srcHeight);
var scale = new SizeF(dest.Width / src.Width, dest.Height / src.Height);
// if we are outside the image, quit now
if (dest.Right < 0 || dest.Left >= this.image.Width || dest.Bottom < 0 || dest.Top >= this.image.Height)
{
return;
}
// crop the bounds so that they are within the image bounds (this is necessary because we have to create a resized version of the cropped source image)
var cropLeft = dest.Left < 0 ? -dest.Left : 0;
var cropTop = dest.Top < 0 ? -dest.Top : 0;
var cropRight = dest.Right >= this.image.Width ? dest.Right - this.image.Width : 0;
var cropBottom = dest.Bottom >= this.image.Height ? dest.Bottom - this.image.Height : 0;
dest = RectangleF.FromLTRB(dest.Left + cropLeft, dest.Top + cropTop, dest.Right - cropRight, dest.Bottom - cropBottom);
src = RectangleF.FromLTRB(src.Left + (cropLeft / scale.Width), src.Top + (cropTop / scale.Height), src.Right - (cropRight / scale.Width), src.Bottom - (cropBottom / scale.Height));
var bytes = source.GetData();
var sourceImage = Image.Load(bytes);
var resampler = interpolate ? KnownResamplers.Triangle : KnownResamplers.NearestNeighbor;
/* The idea now is to roughly crop the source before we resize and then precisely crop it, before drawing it onto the target
* The steps required are:
* - Crop the source image to -1/+2 pixel bounds (may need to increase these bounds depending on the resampler)
* - Add a one pixel 'mirror' border, so that we can a clamped edge when interpolating
* - Resize the source image by the appropriate scale with the appropriate resampler, simultaneously offseting by the non-integer parts of dest and src
* - Crop to exactly what we want
* - Draw the source image onto the destination image
*/
var doPad = interpolate;
var srcRough = new Rectangle((int)Math.Floor(src.X), (int)Math.Floor(src.Y), (int)Math.Ceiling(src.Width + 3), (int)Math.Ceiling(src.Height + 3));
srcRough.Intersect(sourceImage.Bounds);
var srcOffset = new PointF(srcRough.X - src.X, srcRough.Y - src.Y);
srcOffset.Offset(0.5f, 0.5f); // texel alignment for resampler
if (doPad)
{
srcOffset.Offset(-1f, -1f); // offset from padding
}
var destOffset = new PointF(dest.X - (float)Math.Floor(dest.X), dest.Y - (float)Math.Floor(dest.Y));
var destRough = new Rectangle(0, 0, (int)Math.Ceiling(dest.Width), (int)Math.Ceiling(dest.Height));
var rescale = new AffineTransformBuilder().AppendTranslation(srcOffset).AppendScale(scale);
try
{
sourceImage.Mutate(img =>
{
img.Crop(srcRough);
if (doPad)
{
img.Pad(srcRough.Width + 2, srcRough.Height + 2);
img.ApplyProcessor(new MirrorPadProcessor());
}
});
sourceImage.Mutate(img =>
{
img.Transform(rescale, resampler);
destRough.Intersect(sourceImage.Bounds);
img.Crop(destRough);
});
this.Target.Mutate(img =>
{
img.DrawImage(sourceImage, new Point((int)dest.X, (int)dest.Y), new GraphicsOptions() { Antialias = interpolate, BlendPercentage = (float)opacity });
});
}
catch (ImageProcessingException)
{
// Swallow: it's probably because we are trying to render outside of the image: https://github.com/SixLabors/ImageSharp/pull/877
// TODO: verify that we are trying to render outside of the image... somehow
// - I don't think this can be done without having to track the ImageSharp code unhealthily closely
}
finally
{
sourceImage.Dispose();
}
}
/// <inheritdoc/>
public override void DrawLine(IList<ScreenPoint> points, OxyColor stroke, double thickness, EdgeRenderingMode edgeRenderingMode, double[] dashArray, LineJoin lineJoin)
{
if (points.Count < 2)
{
return;
}
var pen = this.GetPen(stroke, thickness, dashArray, edgeRenderingMode, lineJoin);
if (pen is null)
{
return;
}
var actualPoints = this.GetActualPoints(points, thickness, edgeRenderingMode).ToArray();
var options = this.CreateDrawingOptions(this.ShouldUseAntiAliasingForLine(edgeRenderingMode, points));
if (this.PointsAreAllTheSame(actualPoints))
{
// return early if all the points are the same, as this causes a crash in ImageSharp
return;
}
this.Target.Mutate(img =>
{
img.DrawLine(options, pen, actualPoints);
});
}
/// <summary>
/// Determines whether all the points in the given collection are the same.
/// </summary>
/// <param name="points">The collection of points to compare.</param>
/// <returns><code>true</code> if all the points compare equal, otherwise <code>false</code>.</returns>
private bool PointsAreAllTheSame(IList<PointF> points)
{
for (int i = 1; i < points.Count; i++)
{
if (points[i] != points[0])
{
return false;
}
}
return true;
}
/// <inheritdoc/>
public override void DrawPolygon(IList<ScreenPoint> points, OxyColor fill, OxyColor stroke, double thickness, EdgeRenderingMode edgeRenderingMode, double[]? dashArray, LineJoin lineJoin)
{
if (points.Count < 2)
{
return;
}
var pen = this.GetPen(stroke, thickness, dashArray, edgeRenderingMode, lineJoin);
var brush = this.GetBrush(fill);
if (pen is null && brush is null)
{
return;
}
var actualPoints = this.GetActualPoints(points, thickness, edgeRenderingMode).ToArray();
var options = this.CreateDrawingOptions(this.ShouldUseAntiAliasingForLine(edgeRenderingMode, points));
this.Target.Mutate(img =>
{
if (brush != null)
{
img.FillPolygon(options, brush, actualPoints);
}
if (pen != null)
{
img.DrawPolygon(options, pen, actualPoints);
}
});
}
/// <summary>
/// Gets a <see cref="Brush"/>.
/// </summary>
/// <param name="fill">The fill color.</param>
/// <returns>A <see cref="Brush"/>, or <code>null</code> if the fill would be invisible.</returns>
private Brush? GetBrush(OxyColor fill)
{
if (!fill.IsVisible())
{
return null;
}
return Brushes.Solid(ToRgba32(fill));
}
/// <summary>
/// Gets a <see cref="Pen"/>.
/// </summary>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness (in device independent units, 1/96 inch).</param>
/// <param name="edgeRenderingMode">The edge rendering mode.</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>
/// <returns>A <see cref="Pen"/>, or <code>null</code> if the stroke would be invisible.</returns>
private Pen? GetPen(OxyColor stroke, double thickness, double[]? dashArray, EdgeRenderingMode edgeRenderingMode, LineJoin lineJoin)
{
if (this.IsStrokeInvisible(stroke, thickness))
{
return null;
}
var actualThickness = this.GetActualThickness(thickness, edgeRenderingMode);
var actualDashArray = dashArray is null ? null : this.ConvertDashArray(dashArray, actualThickness);
var actualJointStyle = this.GetLineJointStyle(lineJoin);
var penOptions = new PenOptions(ToRgba32(stroke), actualThickness, actualDashArray)
{
JointStyle = actualJointStyle,
};
return new PatternPen(penOptions);
}
/// <summary>
/// Converts a <see cref="LineJoin" /> to a <see cref="JointStyle"/>.
/// </summary>
/// <param name="lineJoin">The line join type.</param>
/// <returns>The converted line join style.</returns>
protected JointStyle GetLineJointStyle(LineJoin lineJoin)
{
switch (lineJoin)
{
case LineJoin.Miter:
return JointStyle.Miter;
case LineJoin.Bevel:
return JointStyle.Square;
case LineJoin.Round:
return JointStyle.Round;
default:
return JointStyle.Miter;
}
}
/// <summary>
/// Determines whether the given color and thickness would be invisible.
/// </summary>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness (in device independent units, 1/96 inch).</param>
/// <returns>True if the stroke would be invisible; otherwise false</returns>
protected bool IsStrokeInvisible(OxyColor stroke, double thickness)
{
return !stroke.IsVisible() || thickness <= 0;
}
/// <inheritdoc/>
protected override void ResetClip()
{
this.EnsureClippedRegion();
this.clipping = false;
}
/// <inheritdoc/>
protected override void SetClip(OxyRect clippingRectangle)
{
var actualRectangle = this.ConvertSnap(clippingRectangle, 0);
this.clippingRectangle = Rectangle.FromLTRB((int)actualRectangle.Left, (int)actualRectangle.Top, (int)actualRectangle.Right, (int)actualRectangle.Bottom);
this.EnsureClippedRegion();
this.clipping = true;
this.Blit(this.image, this.clipImage, this.clippingRectangle);
}
/// <inheritdoc />
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the object.
/// </summary>
/// <param name="disposing">Whether this method is being called from Dispose.</param>
protected virtual void Dispose(bool disposing)
{
if (!this.disposedValue)
{
if (disposing)
{
this.image.Dispose();
this.clipImage.Dispose();
}
this.disposedValue = true;
}
}
/// <summary>
/// Translates an <see cref="OxyColor"/> to a <see cref="Rgba32"/>.
/// </summary>
/// <param name="color">The <see cref="OxyColor"/>.</param>
/// <returns>The resulting <see cref="Rgba32"/>.</returns>
private static Rgba32 ToRgba32(OxyColor color)
{
return new Rgba32(color.R, color.G, color.B, color.A);
}
/// <summary>
/// Gets the pixel offset that a line with the specified thickness should snap to.
/// </summary>
/// <remarks>
/// This takes into account that lines with even stroke thickness should be snapped to the border between two pixels while lines with odd stroke thickness should be snapped to the middle of a pixel.
/// </remarks>
/// <param name="thickness">The line thickness.</param>
/// <returns>The snap offset.</returns>
private static float GetSnapOffset(float thickness)
{
var mod = thickness % 2;
var isOdd = mod >= 0.5 && mod < 1.5;
return isOdd ? 0.5f : 0;
}
/// <summary>
/// Snaps a value to a pixel with the specified offset.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="offset">The offset.</param>
/// <returns>The snapped value.</returns>
private static float Snap(float value, float offset)
{
return (float)Math.Round(value + offset, MidpointRounding.AwayFromZero) - offset;
}
/// <summary>
/// Counts the number of lines in the text.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>The number of lines in the text.</returns>
private static int CountLines(string text)
{
return StringHelper.SplitLines(text).Length;
}
/// <summary>
/// Copies the current clipping rectangle from the <see cref="clipImage"/> to the <see cref="image" />.
/// </summary>
private void EnsureClippedRegion()
{
if (this.clipping)
{
this.Blit(this.clipImage, this.image, this.clippingRectangle);
}
}
/// <summary>
/// Copies pixel values from one image to another within a given rectangle.
/// </summary>
/// <param name="source">The <see cref="Image{Rgba32}" /> from which to copy.</param>
/// <param name="destination">The <see cref="Image{Rgba32}" /> to which to copy.</param>
/// <param name="rectangle">The region to copy.</param>
private void Blit(Image<Rgba32> source, Image<Rgba32> destination, Rectangle rectangle)
{
rectangle.Intersect(source.Bounds);
for (int i = rectangle.Left; i < rectangle.Right; i++)
{
for (int j = rectangle.Top; j < rectangle.Bottom; j++)
{
destination[i, j] = source[i, j];
}
}
}
private Font GetFontOrThrow(string? fontFamily, double fontSize, FontStyle fontWeight, bool allowFallback = true)
{
var family = this.GetFamilyOrFallbackOrThrow(fontFamily, allowFallback);
var actualFontSize = this.NominalFontSizeToPoints(fontSize);
return new Font(family, (float)actualFontSize, fontWeight);
}
private FontFamily GetFamilyOrFallbackOrThrow(string? fontFamily = null, bool allowFallback = true)
{
if (fontFamily == null)
{
allowFallback = false;
fontFamily = FallbackFontFamily;
}
FontFamily family;
try
{
family = SixLabors.Fonts.SystemFonts.Get(fontFamily);
}
catch (FontFamilyNotFoundException primaryEx)
{
if (!allowFallback)
{
throw;
}
try
{
family = SystemFonts.Get(FallbackFontFamily);
}
catch (FontFamilyNotFoundException fallbackEx)
{
throw new AggregateException(primaryEx, fallbackEx);
}
}
return family;
}
/// <summary>
/// Measures the text as it will be arranged out by OxyPlot.
/// </summary>
/// <param name="text">The text to render.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">The font size in points.</param>
/// <param name="fontWeight">The font weight.</param>
/// <returns>An <see cref="OxySize"/>.</returns>
private OxySize MeasureTextLoose(string text, string fontFamily, double fontSize, double fontWeight)
{
text = text ?? string.Empty;
var font = this.GetFontOrThrow(fontFamily, fontSize, this.ToFontStyle(fontWeight));
var actualFontSize = this.NominalFontSizeToPoints(fontSize);
var tight = this.MeasureTextTight(text, fontFamily, fontSize, fontWeight);
var width = tight.Width;
var lineHeight = actualFontSize * this.MilliPointsToNominalResolution(font.FontMetrics.VerticalMetrics.LineHeight);
var lineGap = actualFontSize * this.MilliPointsToNominalResolution(font.FontMetrics.VerticalMetrics.LineGap);
var lineCount = CountLines(text);
var height = (lineHeight * lineCount) + (lineGap * (lineCount - 1));
return new OxySize(width, height);
}
/// <summary>
/// Measures the text as it will be rendered by ImageSharp.
/// </summary>
/// <param name="text">The text to render.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">The font size in points.</param>
/// <param name="fontWeight">The font weight.</param>
/// <returns>An <see cref="OxySize"/>.</returns>
private OxySize MeasureTextTight(string text, string fontFamily, double fontSize, double fontWeight)
{
text = text ?? string.Empty;
var font = this.GetFontOrThrow(fontFamily, fontSize, this.ToFontStyle(fontWeight));
var actualFontSize = this.NominalFontSizeToPoints(fontSize);
var result = TextMeasurer.MeasureSize(text, new TextOptions(font) { Dpi = this.Dpi });
return new OxySize(this.ConvertBack(result.Width), this.ConvertBack(result.Height));
}
/// <summary>
/// Gets the snapping offset for the specified stroke thickness.
/// </summary>
/// <remarks>
/// This takes into account that lines with even stroke thickness should be snapped to the border between two pixels while lines with odd stroke thickness should be snapped to the middle of a pixel.
/// </remarks>
/// <param name="thickness">The stroke thickness.</param>
/// <param name="edgeRenderingMode">The edge rendering mode.</param>
/// <returns>The snap offset.</returns>
private float GetSnapOffset(double thickness, EdgeRenderingMode edgeRenderingMode)
{
var actualThickness = this.GetActualThickness(thickness, edgeRenderingMode);
return GetSnapOffset(actualThickness);
}
/// <summary>
/// Converts millipoints (thousanths of 1/72nds of an inch) to pixels at 96 dots per inch.
/// </summary>
/// <param name="milliPoints">The number of milliPoints.</param>
/// <returns>Pixels at the nominal resolution of 96 dots per inch. </returns>
private double MilliPointsToNominalResolution(int milliPoints)
{
return milliPoints * (0.75 / 1000);
}
/// <summary>
/// Converts nominal font sizes (1/96ths of an inch) to points (1/72nds of an inch).
/// </summary>
/// <param name="fontSize">The nominal font size, in units of 1/96th of an inch.</param>
/// <returns>The font size in points.</returns>
private double NominalFontSizeToPoints(double fontSize)
{
return fontSize * 0.75;
}
/// <summary>
/// Determines an appropriate <see cref="FontStyle"/> to approximate the given font weight.
/// </summary>
/// <param name="fontWeight">The font weight.</param>
/// <returns>The <see cref="FontStyle"/> that approximates the given font weight.</returns>
private FontStyle ToFontStyle(double fontWeight)
{
return fontWeight < 700 ? FontStyle.Regular : FontStyle.Bold;
}
/// <summary>
/// Converts a <see cref="OxyRect"/> to a <see cref="RectangleF"/>, taking into account DPI scaling.
/// </summary>
/// <param name="rect">The rectangle.</param>
/// <returns>The converted rectangle.</returns>
private RectangleF Convert(OxyRect rect)
{
var left = this.Convert(rect.Left);
var right = this.Convert(rect.Right);
var top = this.Convert(rect.Top);
var bottom = this.Convert(rect.Bottom);
return RectangleF.FromLTRB(left, top, right, bottom);
}
/// <summary>
/// Converts a <see cref="double"/> to a <see cref="float"/>, taking into account DPI scaling.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The converted value.</returns>
private float Convert(double value)
{
return (float)value * this.DpiScale;
}
/// <summary>
/// Converts <see cref="ScreenPoint"/> to a <see cref="PointF"/>, taking into account DPI scaling.
/// </summary>
/// <param name="point">The point.</param>
/// <returns>The converted point.</returns>
private PointF Convert(ScreenPoint point)
{
return new PointF(this.Convert(point.X), this.Convert(point.Y));
}
/// <summary>
/// Converts a <see cref="float"/> to a <see cref="double"/>, applying reversed DPI scaling.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The converted value.</returns>
private double ConvertBack(float value)
{
return value / this.DpiScale;
}
/// <summary>
/// Converts <see cref="double"/> dash array to a <see cref="float"/> array, taking into account DPI scaling.
/// </summary>
/// <param name="values">The array of values.</param>
/// <param name="strokeThickness">The stroke thickness.</param>
/// <returns>The array of converted values.</returns>
private float[] ConvertDashArray(double[] values, float strokeThickness)
{
var ret = new float[values.Length];
for (var i = 0; i < values.Length; i++)
{
ret[i] = this.Convert(values[i]) * strokeThickness;
}
return ret;
}
/// <summary>
/// Converts a <see cref="OxyRect"/> to a <see cref="RectangleF"/>, taking into account DPI scaling and snapping the corners to pixels.
/// </summary>
/// <param name="rect">The rectangle.</param>
/// <param name="snapOffset">The snapping offset.</param>
/// <returns>The converted rectangle.</returns>
private RectangleF ConvertSnap(OxyRect rect, float snapOffset)
{
var left = this.ConvertSnap(rect.Left, snapOffset);
var right = this.ConvertSnap(rect.Right, snapOffset);
var top = this.ConvertSnap(rect.Top, snapOffset);
var bottom = this.ConvertSnap(rect.Bottom, snapOffset);
return RectangleF.FromLTRB(left, top, right, bottom);
}
/// <summary>
/// Converts a <see cref="double"/> to a <see cref="float"/>, taking into account DPI scaling and snapping the value to a pixel.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="snapOffset">The snapping offset.</param>
/// <returns>The converted value.</returns>
private float ConvertSnap(double value, float snapOffset)
{
return Snap(this.Convert(value), snapOffset);
}
/// <summary>
/// Converts <see cref="ScreenPoint"/> to a <see cref="PointF"/>, taking into account DPI scaling and snapping the point to a pixel.
/// </summary>
/// <param name="point">The point.</param>
/// <param name="snapOffset">The snapping offset.</param>
/// <returns>The converted point.</returns>
private PointF ConvertSnap(ScreenPoint point, float snapOffset)
{
return new PointF(this.ConvertSnap(point.X, snapOffset), this.ConvertSnap(point.Y, snapOffset));
}
/// <summary>
/// Gets the <see cref="PointF"/>s that should actually be rendered from the list of <see cref="ScreenPoint"/>s, taking into account DPI scaling and snapping if necessary.
/// </summary>
/// <param name="screenPoints">The points.</param>
/// <param name="strokeThickness">The stroke thickness.</param>
/// <param name="edgeRenderingMode">The edge rendering mode.</param>
/// <returns>The actual points.</returns>
private IEnumerable<PointF> GetActualPoints(IList<ScreenPoint> screenPoints, double strokeThickness, EdgeRenderingMode edgeRenderingMode)
{
switch (edgeRenderingMode)
{
case EdgeRenderingMode.Automatic when RenderContextBase.IsStraightLine(screenPoints):
case EdgeRenderingMode.Adaptive when RenderContextBase.IsStraightLine(screenPoints):
case EdgeRenderingMode.PreferSharpness:
var snapOffset = this.GetSnapOffset(strokeThickness, edgeRenderingMode);
return screenPoints.Select(p => this.ConvertSnap(p, snapOffset));
default:
return screenPoints.Select(this.Convert);
}
}
/// <summary>
/// Gets the stroke thickness that should actually be used for rendering, taking into account DPI scaling and snapping if necessary.
/// </summary>
/// <param name="strokeThickness">The stroke thickness.</param>
/// <param name="edgeRenderingMode">The edge rendering mode.</param>
/// <returns>The actual stroke thickness.</returns>
private float GetActualThickness(double strokeThickness, EdgeRenderingMode edgeRenderingMode)
{
var scaledThickness = this.Convert(strokeThickness);
if (edgeRenderingMode == EdgeRenderingMode.PreferSharpness)
{
scaledThickness = Snap(scaledThickness, 0);
}
return scaledThickness;
}
/// <summary>
/// Creates a <see cref="DrawingOptions"/> object for the given options.
/// </summary>
/// <param name="antialised">A value indicating whether graphics should be antialised.</param>
/// <returns>A new <see cref="DrawingOptions"/></returns>
private DrawingOptions CreateDrawingOptions(bool antialised)
{
var options = new DrawingOptions()
{
GraphicsOptions = new GraphicsOptions()
{
Antialias = antialised
}
};
return options;
}
}
}