SwiftUI: How can I save hand drawing as UIImage

Viewed 233

Example Drawing

This code creates free hand drawing function. I want to save this hand drawing to camera roll.

Is it possible to convert drawing image to UIImage?

struct Drawings {
    var points: [CGPoint] = [CGPoint]()
}


struct DrawingPad: View {
    @Binding var currentDrawing: Drawings
    @Binding var drawings: [Drawings]
    @Binding var color: Color
    @Binding var lineWidth: CGFloat
    
    var body: some View {
        GeometryReader { geometry in
            
            Path{ path in
                for drawing in self.drawings {
                    self.add(drawing: drawing, toPath: &path)
                }
                self.add(drawing: self.currentDrawing, toPath: &path)

                }
            
            .stroke(self.color, lineWidth: self.lineWidth)
            .background(Color(white: 0.95))
            .gesture(
              DragGesture(minimumDistance: 0.1)
                    .onChanged({ (value) in
                        let currentPoint = value.location
                        if currentPoint.y >= 0
                            && currentPoint.y < geometry.size.height {
                            self.currentDrawing.points.append(currentPoint)
                        }
                    })
                    .onEnded({ (value) in
                        self.drawings.append(self.currentDrawing)
                        self.currentDrawing = Drawings()
                    })
               )
        }
        .frame(maxHeight: .infinity)
    }
    
    private func add(drawing: Drawings, toPath path: inout Path) {
        
        let points = drawing.points
        
        if points.count > 1 {
            for i in 0..<points.count-1 {
                let current = points[i]
                let next = points[i+1]
                path.move(to: current)
                path.addLine(to: next)
            }
        }
    }
    
}
0 Answers
Related