Advertisement
Guest User

DrawingController

a guest
Sep 22nd, 2019
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.63 KB | None | 0 0
  1. //
  2. //  LoginViewController.swift
  3. //  First screen
  4. //
  5. //  Created by karolis on 21/09/2019.
  6. //  Copyright © 2019 karolis. All rights reserved.
  7. //
  8.  
  9.  
  10.  
  11. import UIKit
  12.  
  13. class DrawingController: UIView {
  14.    
  15.     override func draw(_ rect: CGRect) {
  16.      
  17.         super.draw(rect)
  18.        
  19.         guard let context = UIGraphicsGetCurrentContext() else { return }
  20.        
  21.        
  22.         context.setStrokeColor(UIColor.red.cgColor)
  23.         context.setLineWidth(10)
  24.         context.setLineCap(.butt)
  25.        
  26.         lines.forEach { (line) in
  27.             for (i, p) in line.enumerated() {
  28.                 if i == 0 {
  29.                     context.move(to: p)
  30.                 } else {
  31.                     context.addLine(to: p)
  32.                 }
  33.             }
  34.         }
  35.        
  36.         context.strokePath()
  37.        
  38.     }
  39.    
  40.    
  41.     var lines = [[CGPoint]]()
  42.    
  43.     override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  44.         lines.append([CGPoint]())
  45.     }
  46.    
  47.     override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
  48.         guard let point = touches.first?.location(in: nil) else { return }
  49.  
  50.         guard var lastLine = lines.popLast() else { return }
  51.         lastLine.append(point)
  52.         lines.append(lastLine)
  53.        
  54.         setNeedsDisplay()
  55.     }
  56.    
  57. }
  58.  
  59. class ViewController: UIViewController {
  60.    
  61.     let canvas = DrawingController()
  62.    
  63.     override func viewDidLoad() {
  64.         super.viewDidLoad()
  65.        
  66.         view.addSubview(canvas)
  67.         canvas.backgroundColor = .white
  68.         canvas.frame = view.frame
  69.     }
  70.    
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement