Swift5.1.3 Xcode11.3 SwiftUI
- how to create digital sketchbook
- Confirm drawing on canvas with continuous dots
- Handle Gesture function to set CGPoint
* Here is the highlight of YouTube tutorial.
Here, I will show you how to create digital sketchbook so that you can
get your original iOS drawing app for free. Let's learn the basic with
SwiftUI.
First, I will use the following 4 variables.
@State var isDrawing: Drawer = Drawer()
@State var drawers: [Drawer] = [Drawer]()
@State var colorSet: Color = Color.blue
@State var drawWidth: CGFloat = 4.0
By using the complex of CGpoint, dot location information, you can get
your sketching line on the canvas. You can also determine the design of
pencil with these parameters.
The drawing data is stored in the following structure. The array of points
works as keeper.
struct Drawer {
var points: [CGPoint] = [CGPoint]()
}
Multiple dots will be connected drawing lines with the function, named
addAction.
func addAction(Drawer: Drawer, toPath linePath: inout Path) {
let points = Drawer.points
if points.count > 1 {
for i in 0..<points.count-1 {
let previous = points[i]
let next = points[i+1]
linePath.move(to: previous)
linePath.addLine(to: next)
}
}
}
To get the location information of dots, let's use gesture function. The
attached function, .onChanged works as this role. On the other hand, .onEnded
works to reset the points array.
Let me summarize the codes so far.
struct DrawingArea: View {
@Binding var isDrawing: Drawer
@Binding var drawers: [Drawer]
@Binding var colorSet: Color
@Binding var drawWidth: CGFloat
var body: some View {
GeometryReader { geometry in
Path { linePath in
for Drawer in self.drawers {
self.addAction(Drawer: Drawer, toPath: &linePath)
}
self.addAction(Drawer: self.isDrawing, toPath: &linePath)
}
.stroke(self.colorSet, lineWidth: self.drawWidth)
.background(Color(white: 0.7))
.gesture(
DragGesture(minimumDistance: 0.05)
.onChanged({ (value) in
let currentPoint = value.location
if currentPoint.y >= 0 && currentPoint.y < geometry.size.height
{
self.isDrawing.points.append(currentPoint)
}
})
.onEnded({ (value) in
self.drawers.append(self.isDrawing)
self.isDrawing = Drawer()
})
)
}
}
func addAction(Drawer: Drawer, toPath linePath: inout Path) {
let points = Drawer.points
if points.count > 1 {
for i in 0..<points.count-1 {
let previous = points[i]
let next = points[i+1]
linePath.move(to: previous)
linePath.addLine(to: next)
}
}
}
}
Finally, the struct above will be used in ContentView. The parameters of
DrawingArea have @Binding at preposition, not @State. The reason is that
you have to determine the position of dots after drawing gesture. To send
the data into ContentView, don't forget $ mark for the parameters.
Build the code and try to change the design of pencil so that you can learn
more.
To get the source code, check the comment of my YouTube
Back to Table List