-
-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathSKControl.cs
101 lines (78 loc) · 2.19 KB
/
SKControl.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
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace SkiaSharp.Views.Desktop
{
[DefaultEvent("PaintSurface")]
[DefaultProperty("Name")]
public class SKControl : Control
{
private readonly bool designMode;
private Bitmap bitmap;
public SKControl()
{
DoubleBuffered = true;
SetStyle(ControlStyles.ResizeRedraw, true);
designMode = DesignMode || LicenseManager.UsageMode == LicenseUsageMode.Designtime;
}
[Bindable(false)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[EditorBrowsable(EditorBrowsableState.Never)]
public SKSize CanvasSize => bitmap == null ? SKSize.Empty : new SKSize(bitmap.Width, bitmap.Height);
[Category("Appearance")]
public event EventHandler<SKPaintSurfaceEventArgs> PaintSurface;
private bool painting = false;
protected override void OnPaint(PaintEventArgs e)
{
if (designMode)
return;
if (painting) return;
painting = true;
base.OnPaint(e);
// get the bitmap
CreateBitmap();
var data = bitmap.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.WriteOnly, bitmap.PixelFormat);
// create the surface
var info = new SKImageInfo(Width, Height, SKImageInfo.PlatformColorType, SKAlphaType.Premul);
using (var surface = SKSurface.Create(info, data.Scan0, data.Stride))
{
// start drawing
OnPaintSurface(new SKPaintSurfaceEventArgs(surface, info));
surface.Canvas.Flush();
}
// write the bitmap to the graphics
bitmap.UnlockBits(data);
e.Graphics.DrawImage(bitmap, 0, 0);
painting = false;
}
protected virtual void OnPaintSurface(SKPaintSurfaceEventArgs e)
{
// invoke the event
PaintSurface?.Invoke(this, e);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
FreeBitmap();
}
private void CreateBitmap()
{
if (bitmap == null || bitmap.Width != Width || bitmap.Height != Height)
{
FreeBitmap();
bitmap = new Bitmap(Width, Height, PixelFormat.Format32bppPArgb);
}
}
private void FreeBitmap()
{
if (bitmap != null)
{
bitmap.Dispose();
bitmap = null;
}
}
}
}