Last active
May 5, 2023 17:07
-
-
Save andresr-dev/50a227936f9da35383a3cd5a0ddc3d9e to your computer and use it in GitHub Desktop.
This is a simple drawing view made with SwiftUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import SwiftUI | |
struct SignatureLine { | |
var points = [CGPoint]() | |
let width = 3.0 | |
} | |
struct DrawingView: View { | |
@State private var lines = [SignatureLine]() | |
@State private var currentLine: SignatureLine? | |
var body: some View { | |
Canvas { context, size in | |
for line in lines { | |
var path = Path() | |
path.addLines(line.points) | |
context.stroke(path, with: .color(.primary), lineWidth: line.width) | |
} | |
} | |
.gesture(dragGesture) | |
} | |
private var dragGesture: some Gesture { | |
DragGesture(minimumDistance: 0) | |
.onChanged(updateLines) | |
.onEnded { _ in | |
currentLine = nil | |
} | |
} | |
private func updateLines(dragValue: DragGesture.Value) { | |
if currentLine == nil { | |
currentLine = SignatureLine() | |
lines.append(currentLine!) | |
} | |
currentLine!.points.append(dragValue.location) | |
guard lines.count > 0 else { return } | |
lines[lines.count - 1].points = currentLine!.points | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment