forked from klokantech/VectorTileRenderer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSkiaCanvas.cs
More file actions
599 lines (495 loc) · 19.5 KB
/
SkiaCanvas.cs
File metadata and controls
599 lines (495 loc) · 19.5 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
using ClipperLib;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace VectorTileRenderer
{
public class SkiaCanvas : ICanvas
{
int width;
int height;
//SKBitmap skBitmap;
WriteableBitmap bitmap;
SKSurface surface;
SKCanvas canvas;
public bool ClipOverflow { get; set; } = false;
private Rect clipRectangle;
List<IntPoint> clipRectanglePath;
Dictionary<string, SKTypeface> fontPairs = new Dictionary<string, SKTypeface>();
List<Rect> textRectangles = new List<Rect>();
public void StartDrawing(double width, double height)
{
this.width = (int)width;
this.height = (int)height;
bitmap = new WriteableBitmap(this.width, this.height, 96, 96, PixelFormats.Pbgra32, null);
bitmap.Lock();
var info = new SKImageInfo(this.width, this.height, SKImageInfo.PlatformColorType, SKAlphaType.Premul);
surface = SKSurface.Create(info, bitmap.BackBuffer, bitmap.BackBufferStride);
canvas = surface.Canvas;
double padding = -5;
clipRectangle = new Rect(padding, padding, this.width - padding * 2, this.height - padding * 2);
clipRectanglePath = new List<IntPoint>();
clipRectanglePath.Add(new IntPoint((int)clipRectangle.Top, (int)clipRectangle.Left));
clipRectanglePath.Add(new IntPoint((int)clipRectangle.Top, (int)clipRectangle.Right));
clipRectanglePath.Add(new IntPoint((int)clipRectangle.Bottom, (int)clipRectangle.Right));
clipRectanglePath.Add(new IntPoint((int)clipRectangle.Bottom, (int)clipRectangle.Left));
}
public void DrawBackground(Brush style)
{
canvas.Clear(new SKColor(style.Paint.BackgroundColor.R, style.Paint.BackgroundColor.G, style.Paint.BackgroundColor.B, style.Paint.BackgroundColor.A));
}
SKStrokeCap convertCap(PenLineCap cap)
{
if (cap == PenLineCap.Flat)
{
return SKStrokeCap.Butt;
}
else if (cap == PenLineCap.Round)
{
return SKStrokeCap.Round;
}
return SKStrokeCap.Square;
}
//private double getAngle(double x1, double y1, double x2, double y2)
//{
// double degrees;
// if (x2 - x1 == 0)
// {
// if (y2 > y1)
// degrees = 90;
// else
// degrees = 270;
// }
// else
// {
// // Calculate angle from offset.
// double riseoverrun = (y2 - y1) / (x2 - x1);
// double radians = Math.Atan(riseoverrun);
// degrees = radians * (180 / Math.PI);
// if ((x2 - x1) < 0 || (y2 - y1) < 0)
// degrees += 180;
// if ((x2 - x1) > 0 && (y2 - y1) < 0)
// degrees -= 180;
// if (degrees < 0)
// degrees += 360;
// }
// return degrees;
//}
//private double getAngleAverage(double a, double b)
//{
// a = a % 360;
// b = b % 360;
// double sum = a + b;
// if (sum > 360 && sum < 540)
// {
// sum = sum % 180;
// }
// return sum / 2;
//}
List<Point> clipPolygon(List<Point> geometry)
{
Clipper c = new Clipper();
var polygon = new List<IntPoint>();
foreach (var point in geometry)
{
polygon.Add(new IntPoint((int)point.X, (int)point.Y));
}
c.AddPolygon(polygon, PolyType.ptSubject);
c.AddPolygon(clipRectanglePath, PolyType.ptClip);
List<List<IntPoint>> solution = new List<List<IntPoint>>();
bool success = c.Execute(ClipType.ctIntersection, solution, PolyFillType.pftNonZero, PolyFillType.pftEvenOdd);
if (success && solution.Count > 0)
{
var result = solution.First().Select(item => new Point(item.X, item.Y)).ToList();
return result;
}
return null;
}
List<Point> clipLine(List<Point> geometry)
{
return LineClipper.ClipPolyline(geometry, clipRectangle);
}
SKPath getPathFromGeometry(List<Point> geometry)
{
SKPath path = new SKPath
{
FillType = SKPathFillType.EvenOdd,
};
var firstPoint = geometry[0];
path.MoveTo((float)firstPoint.X, (float)firstPoint.Y);
foreach (var point in geometry.Skip(1))
{
var lastPoint = path.LastPoint;
path.LineTo((float)point.X, (float)point.Y);
}
return path;
}
public void DrawLineString(List<Point> geometry, Brush style)
{
if (ClipOverflow)
{
geometry = clipLine(geometry);
if (geometry == null)
{
return;
}
}
var path = getPathFromGeometry(geometry);
if(path == null)
{
return;
}
SKPaint fillPaint = new SKPaint
{
Style = SKPaintStyle.Stroke,
StrokeCap = convertCap(style.Paint.LineCap),
StrokeWidth = (float)style.Paint.LineWidth,
Color = new SKColor(style.Paint.LineColor.R, style.Paint.LineColor.G, style.Paint.LineColor.B, (byte)(style.Paint.LineColor.A * style.Paint.LineOpacity)),
IsAntialias = true,
};
if(style.Paint.LineDashArray.Count() > 0)
{
var effect = SKPathEffect.CreateDash(style.Paint.LineDashArray.Select(n => (float)n).ToArray(), 0);
fillPaint.PathEffect = effect;
}
//Console.WriteLine(style.Paint.LineWidth);
canvas.DrawPath(path, fillPaint);
}
SKTextAlign convertAlignment(TextAlignment alignment)
{
if (alignment == TextAlignment.Center)
{
return SKTextAlign.Center;
}
else if (alignment == TextAlignment.Left)
{
return SKTextAlign.Left;
}
else if (alignment == TextAlignment.Right)
{
return SKTextAlign.Right;
}
return SKTextAlign.Center;
}
SKPaint getTextStrokePaint(Brush style)
{
var paint = new SKPaint()
{
IsStroke = true,
StrokeWidth = (float)style.Paint.TextStrokeWidth,
Color = new SKColor(style.Paint.TextStrokeColor.R, style.Paint.TextStrokeColor.G, style.Paint.TextStrokeColor.B, (byte)(style.Paint.TextStrokeColor.A * style.Paint.TextOpacity)),
TextSize = (float)style.Paint.TextSize,
IsAntialias = true,
TextEncoding = SKTextEncoding.Utf32,
TextAlign = convertAlignment(style.Paint.TextJustify),
Typeface = getFont(style.Paint.TextFont, style),
};
return paint;
}
SKPaint getTextPaint(Brush style)
{
var paint = new SKPaint()
{
Color = new SKColor(style.Paint.TextColor.R, style.Paint.TextColor.G, style.Paint.TextColor.B, (byte)(style.Paint.TextColor.A * style.Paint.TextOpacity)),
TextSize = (float)style.Paint.TextSize,
IsAntialias = true,
TextEncoding = SKTextEncoding.Utf32,
TextAlign = convertAlignment(style.Paint.TextJustify),
Typeface = getFont(style.Paint.TextFont, style),
};
return paint;
}
string transformText(string text, Brush style)
{
if(text.Length == 0)
{
return "";
}
if(style.Paint.TextTransform == TextTransform.Uppercase)
{
text = text.ToUpper();
} else if (style.Paint.TextTransform == TextTransform.Lowercase)
{
text = text.ToLower();
}
var paint = getTextPaint(style);
text = breakText(text, paint, style);
return text;
//return Encoding.UTF32.GetBytes(newText);
}
string breakText(string input, SKPaint paint, Brush style)
{
var restOfText = input;
var brokenText = "";
do
{
var lineLength = paint.BreakText(restOfText, (float)(style.Paint.TextMaxWidth * style.Paint.TextSize));
if(lineLength == restOfText.Length)
{
// its the end
brokenText += restOfText.Trim();
break;
}
var lastSpaceIndex = restOfText.LastIndexOf(' ', (int)(lineLength - 1));
if(lastSpaceIndex == -1 || lastSpaceIndex == 0)
{
// no more spaces, probably ;)
brokenText += restOfText.Trim();
break;
}
brokenText += restOfText.Substring(0, (int)lastSpaceIndex).Trim() + "\n";
restOfText = restOfText.Substring((int)lastSpaceIndex, restOfText.Length - (int)lastSpaceIndex);
} while (restOfText.Length > 0);
return brokenText.Trim();
}
bool textCollides(Rect rectangle)
{
foreach(var rect in textRectangles)
{
if(rect.IntersectsWith(rectangle))
{
return true;
}
}
return false;
}
SKTypeface getFont(string[] familyNames, Brush style)
{
foreach (var name in familyNames)
{
if (fontPairs.ContainsKey(name))
{
return fontPairs[name];
}
if (style.GlyphsDirectory != null)
{
// check file system for ttf
var newType = SKTypeface.FromFile(System.IO.Path.Combine(style.GlyphsDirectory, name + ".ttf"));
if (newType != null)
{
fontPairs[name] = newType;
return newType;
}
// check file system for otf
newType = SKTypeface.FromFile(System.IO.Path.Combine(style.GlyphsDirectory, name + ".otf"));
if (newType != null)
{
fontPairs[name] = newType;
return newType;
}
}
var typeface = SKTypeface.FromFamilyName(name);
if (typeface.FamilyName == name)
{
// gotcha!
fontPairs[name] = typeface;
return typeface;
}
}
// all options exhausted...
// get the first one
var fallback = SKTypeface.FromFamilyName(familyNames.First());
fontPairs[familyNames.First()] = fallback;
return fallback;
}
public void DrawText(Point geometry, Brush style)
{
if(style.Paint.TextOptional)
{
// TODO check symbol collision
//return;
}
var paint = getTextPaint(style);
var strokePaint = getTextStrokePaint(style);
var text = transformText(style.Text, style);
var allLines = text.Split('\n');
// detect collisions
if(allLines.Length > 0)
{
var biggestLine = allLines.OrderBy(line => line.Length).Last();
var bytes = Encoding.UTF32.GetBytes(biggestLine);
var width = (int)(paint.MeasureText(bytes));
int left = (int)(geometry.X - width / 2);
int top = (int)(geometry.Y - style.Paint.TextSize/2 * allLines.Length);
int height = (int)(style.Paint.TextSize * allLines.Length);
var rectangle = new Rect(left, top, width, height);
rectangle.Inflate(5, 5);
if(ClipOverflow)
{
if(!clipRectangle.Contains(rectangle))
{
return;
}
}
if (textCollides(rectangle))
{
// collision detected
return;
}
textRectangles.Add(rectangle);
//var list = new List<Point>()
//{
// rectangle.TopLeft,
// rectangle.TopRight,
// rectangle.BottomRight,
// rectangle.BottomLeft,
//};
//var brush = new Brush();
//brush.Paint = new Paint();
//brush.Paint.FillColor = Color.FromArgb(150, 255, 0, 0);
//this.DrawPolygon(list, brush);
}
int i = 0;
foreach (var line in allLines)
{
var bytes = Encoding.UTF32.GetBytes(line);
float lineOffset = (float)(i * style.Paint.TextSize) - ((float)(allLines.Length) * (float)style.Paint.TextSize) / 2 + (float)style.Paint.TextSize;
var position = new SKPoint((float)geometry.X + (float)(style.Paint.TextOffset.X * style.Paint.TextSize), (float)geometry.Y + (float)(style.Paint.TextOffset.Y * style.Paint.TextSize) + lineOffset);
if (style.Paint.TextStrokeWidth != 0)
{
canvas.DrawText(bytes, position, strokePaint);
}
canvas.DrawText(bytes, position, paint);
i++;
}
}
public void DrawTextOnPath(List<Point> geometry, Brush style)
{
// buggggyyyyyy
// requires an amazing collision system to work :/
// --
return;
if (ClipOverflow)
{
geometry = clipLine(geometry);
if (geometry == null)
{
return;
}
}
var path = getPathFromGeometry(geometry);
var text = transformText(style.Text, style);
var left = geometry.Min(item => item.X) - style.Paint.TextSize;
var top = geometry.Min(item => item.Y) - style.Paint.TextSize;
var right = geometry.Max(item => item.X) + style.Paint.TextSize;
var bottom = geometry.Max(item => item.Y) + style.Paint.TextSize;
var rectangle = new Rect(left, top, right - left, bottom - top);
if (textCollides(rectangle))
{
// collision detected
return;
}
textRectangles.Add(rectangle);
//var list = new List<Point>()
//{
// rectangle.TopLeft,
// rectangle.TopRight,
// rectangle.BottomRight,
// rectangle.BottomLeft,
//};
//var brush = new Brush();
//brush.Paint = new Paint();
//brush.Paint.FillColor = Color.FromArgb(150, 255, 0, 0);
//this.DrawPolygon(list, brush);
var offset = new SKPoint((float)style.Paint.TextOffset.X, (float)style.Paint.TextOffset.Y);
var bytes = Encoding.UTF32.GetBytes(text);
if (style.Paint.TextStrokeWidth != 0)
{
canvas.DrawTextOnPath(bytes, path, offset, getTextStrokePaint(style));
}
canvas.DrawTextOnPath(bytes, path, offset, getTextPaint(style));
}
public void DrawPoint(Point geometry, Brush style)
{
if(style.Paint.IconImage != null)
{
// draw icon here
}
}
public void DrawPolygon(List<Point> geometry, Brush style)
{
if (ClipOverflow)
{
geometry = clipPolygon(geometry);
if (geometry == null)
{
return;
}
}
var path = getPathFromGeometry(geometry);
if (path == null)
{
return;
}
SKPaint fillPaint = new SKPaint
{
Style = SKPaintStyle.Fill,
StrokeCap = convertCap(style.Paint.LineCap),
Color = new SKColor(style.Paint.FillColor.R, style.Paint.FillColor.G, style.Paint.FillColor.B, (byte)(style.Paint.FillColor.A * style.Paint.FillOpacity)),
IsAntialias = true,
};
canvas.DrawPath(path, fillPaint);
}
static SKImage toSKImage(BitmapSource bitmap)
{
// TODO: maybe keep the same color types where we can, instead of just going to the platform default
var info = new SKImageInfo(bitmap.PixelWidth, bitmap.PixelHeight);
var image = SKImage.Create(info);
using (var pixmap = image.PeekPixels())
{
toSKPixmap(bitmap, pixmap);
}
return image;
}
static void toSKPixmap(BitmapSource bitmap, SKPixmap pixmap)
{
// TODO: maybe keep the same color types where we can, instead of just going to the platform default
if (pixmap.ColorType == SKImageInfo.PlatformColorType)
{
var info = pixmap.Info;
var converted = new FormatConvertedBitmap(bitmap, PixelFormats.Pbgra32, null, 0);
converted.CopyPixels(new Int32Rect(0, 0, info.Width, info.Height), pixmap.GetPixels(), info.BytesSize, info.RowBytes);
}
else
{
// we have to copy the pixels into a format that we understand
// and then into a desired format
// TODO: we can still do a bit more for other cases where the color types are the same
using (var tempImage = toSKImage(bitmap))
{
tempImage.ReadPixels(pixmap, 0, 0);
}
}
}
public void DrawImage(Stream imageStream, Brush style)
{
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = imageStream;
bitmapImage.DecodePixelWidth = this.width;
bitmapImage.DecodePixelHeight = this.height;
bitmapImage.EndInit();
var image = toSKImage(bitmapImage);
canvas.DrawImage(image, new SKPoint(0, 0));
}
public void DrawUnknown(List<List<Point>> geometry, Brush style)
{
}
public BitmapSource FinishDrawing()
{
bitmap.AddDirtyRect(new Int32Rect(0, 0, this.width, this.height));
bitmap.Unlock();
bitmap.Freeze();
return bitmap;
}
}
}