-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day16-PKCanvasView.swift
138 lines (119 loc) · 4.33 KB
/
Day16-PKCanvasView.swift
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
//
// ContentView.swift
// Pencil
//
// Created by Dali Han on 2020/8/4.
// Copyright © 2020 Dali Han. All rights reserved.
// Credit to Kavsoft
// Link: https://www.youtube.com/watch?v=LR-ttBoa89M
import SwiftUI
import PencilKit
struct ContentView: View {
var body: some View {
Home()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct Home: View {
@State var canvas = PKCanvasView()
@State var isDraw = true
@State var color: Color = .black
@State var type: PKInkingTool.InkType = .pencil
@State var colorPicker = false
var body: some View {
NavigationView {
DrawingView(canvas: $canvas, isDraw: $isDraw, type: $type, color: $color)
.navigationTitle("Drawing")
.navigationBarTitleDisplayMode(.inline)
.navigationBarItems(leading: Button(action: {
// saving images
}) {
Image(systemName: "square.and.arrow.down.fill")
.font(.title)
}, trailing: HStack(spacing: 15) {
Button(action: {
// eraser tool
isDraw = false
}) {
Image(systemName: "pencil.tip.crop.circle.badge.minus")
.font(.title)
}
// Menu
Menu {
Button(action: {
colorPicker.toggle()
}) {
Label {
Text("Color")
} icon: {
Image(systemName: "eyedropper.halffull")
}
}
Button(action: {
isDraw = true
type = .pencil
}) {
Label {
Text("Pencil")
} icon: {
Image(systemName: "pencil")
}
}
Button(action: {
isDraw = true
type = .pen
}) {
Label {
Text("Pen")
} icon: {
Image(systemName: "pencil.tip")
}
}
Button(action: {
isDraw = true
type = .marker
}) {
Label {
Text("Marker")
} icon: {
Image(systemName: "highlighter")
}
}
} label: {
Image(systemName: "pencil")
.resizable()
// .frame(width: 25, height: 25)
}
})
.sheet(isPresented: $colorPicker) {
ColorPicker("Pick a Color", selection: $color)
}
}.padding()
}
func SaveImage() {
let image = canvas.drawing.image(from: canvas.drawing.bounds, scale: 1)
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
}
struct DrawingView : UIViewRepresentable {
@Binding var canvas : PKCanvasView
@Binding var isDraw : Bool
@Binding var type : PKInkingTool.InkType
@Binding var color : Color
var ink: PKInkingTool {
PKInkingTool(type, color: UIColor(color))
}
let eraser = PKEraserTool(.bitmap)
func makeUIView(context: Context) -> PKCanvasView {
canvas.drawingPolicy = .anyInput
canvas.tool = isDraw ? ink : eraser
return canvas
}
func updateUIView(_ uiView: PKCanvasView, context: Context) {
uiView.tool = isDraw ? ink : eraser
}
}