1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| class DrawViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var lastPoint = CGPoint.zero
var swiped = false
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){
swiped = false
if let touch = touches.first {
lastPoint = touch.location(in: self.view)
}
}
func drawLines(fromPoint:CGPoint,toPoint:CGPoint) {
UIGraphicsBeginImageContext(self.view.frame.size)
imageView.image?.draw(in: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
// imageView.image?.draw(in: view.bounds)
let context = UIGraphicsGetCurrentContext()
context?.move(to: CGPoint(x: fromPoint.x, y: fromPoint.y))
context?.addLine(to: CGPoint(x: toPoint.x, y: toPoint.y))
// context.move(to: fromPoint)
// context.addLine(to: toPoint)
context?.setBlendMode(CGBlendMode.normal)
context?.setLineCap(CGLineCap.round)
context?.setLineWidth(5.0)
context?.setStrokeColor(UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0).cgColor)
context?.strokePath()
imageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?){
swiped = true
if let touch = touches.first {
let currentPoint = touch.location(in: self.view)
drawLines(fromPoint: lastPoint, toPoint: currentPoint)
lastPoint = currentPoint
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?){ if !swiped { drawLines(fromPoint: lastPoint, toPoint: lastPoint) } }
override func viewDidLoad() {super.viewDidLoad()}
override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()} |
Partager