// // ContentView.swift // SwiftMnist // // Created by Miguel de Icaza on 6/1/20. // Copyright © 2020 Miguel de Icaza. All rights reserved. // import SwiftUI import CoreGraphics let factor:CGFloat = 6.0 struct Drawing { var points: [CGPoint] = [CGPoint]() } struct DrawingPad: View { @Binding var currentDrawing: Drawing @Binding var drawings: [Drawing] @Binding var guesses: [Float] @Binding var result: Int func updateGuess () { // Render the vector to a bitmap of ours let ctx = CGContext.init(data: nil, width: 28, height: 28, bitsPerComponent: 8, bytesPerRow: 28*4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)! ctx.translateBy(x: 0, y: 28) ctx.scaleBy(x: 1, y: -1) ctx.setStrokeColor(NSColor.black.cgColor) for drawing in self.drawings { if drawing.points.count < 2 { continue } let mapped = drawing.points.map { CGPoint (x: $0.x/factor, y: $0.y/factor) } ctx.beginPath() ctx.move(to: mapped [0]) for i in 1..= 0 && currentPoint.y < geometry.size.height { self.currentDrawing.points.append(currentPoint) } self.updateGuess () }) .onEnded({ (value) in self.drawings.append(self.currentDrawing) self.currentDrawing = Drawing() self.updateGuess () }) ) } .frame(maxHeight: .infinity) } private func add(drawing: Drawing, toPath path: inout Path) { let points = drawing.points if points.count > 1 { for i in 0..String { let v = guesses [idx] return (v >= 0 ? " " : "") + String(format: "%2.2f", v) } var body: some View { VStack(alignment: .center) { Text("Draw a digit") .font(.largeTitle) HStack { DrawingPad( currentDrawing: $currentDrawing, drawings: $drawings, guesses: $guesses, result: $result) .frame(width: 24*factor, height: 24*factor) .border(Color.black) VStack { ForEach (guesses.indices) { idx in HStack { Text ("x") Rectangle () .offset (x: 10) .border(Color.red) .frame(width:40, height: 20) } } }.frame (width: 120) VStack (alignment: .leading) { Text ("Result: \(result)") ForEach (guesses.indices) { idx in Text ("\(idx) -> \(self.fmt (idx))") } }.frame(width: 120) } .font(.system(Font.TextStyle.body, design: .monospaced)) Button(action: {self.drawings = []; self.guesses = Array.init (repeating: 0, count: 10)}) { Text ("Clear") } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }