PhotoEditor+Drawing.swift 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // PhotoEditor+Drawing.swift
  3. // Photo Editor
  4. //
  5. // Created by Mohamed Hamed on 6/16/17.
  6. //
  7. //
  8. import UIKit
  9. extension PhotoEditorViewController {
  10. override public func touchesBegan(_ touches: Set<UITouch>,
  11. with event: UIEvent?){
  12. if isDrawing {
  13. swiped = false
  14. if let touch = touches.first {
  15. lastPoint = touch.location(in: self.canvasImageView)
  16. }
  17. }
  18. //Hide stickersVC if clicked outside it
  19. else if stickersVCIsVisible == true {
  20. if let touch = touches.first {
  21. let location = touch.location(in: self.view)
  22. if !stickersViewController.view.frame.contains(location) {
  23. removeStickersView()
  24. }
  25. }
  26. }
  27. }
  28. override public func touchesMoved(_ touches: Set<UITouch>,
  29. with event: UIEvent?){
  30. if isDrawing {
  31. // 6
  32. swiped = true
  33. if let touch = touches.first {
  34. let currentPoint = touch.location(in: canvasImageView)
  35. drawLineFrom(lastPoint, toPoint: currentPoint)
  36. // 7
  37. lastPoint = currentPoint
  38. }
  39. }
  40. }
  41. override public func touchesEnded(_ touches: Set<UITouch>,
  42. with event: UIEvent?){
  43. if isDrawing {
  44. if !swiped {
  45. // draw a single point
  46. drawLineFrom(lastPoint, toPoint: lastPoint)
  47. }
  48. }
  49. }
  50. func drawLineFrom(_ fromPoint: CGPoint, toPoint: CGPoint) {
  51. // 1
  52. let canvasSize = canvasImageView.frame.integral.size
  53. UIGraphicsBeginImageContextWithOptions(canvasSize, false, 0)
  54. if let context = UIGraphicsGetCurrentContext() {
  55. canvasImageView.image?.draw(in: CGRect(x: 0, y: 0, width: canvasSize.width, height: canvasSize.height))
  56. // 2
  57. context.move(to: CGPoint(x: fromPoint.x, y: fromPoint.y))
  58. context.addLine(to: CGPoint(x: toPoint.x, y: toPoint.y))
  59. // 3
  60. context.setLineCap( CGLineCap.round)
  61. context.setLineWidth(5.0)
  62. context.setStrokeColor(drawColor.cgColor)
  63. context.setBlendMode( CGBlendMode.normal)
  64. // 4
  65. context.strokePath()
  66. // 5
  67. canvasImageView.image = UIGraphicsGetImageFromCurrentImageContext()
  68. }
  69. UIGraphicsEndImageContext()
  70. }
  71. }