1

I want to let the User to draw a rectangle on UIImageView I added two variables for first an last touch locations I added this function:-

func draw(from: CGPoint, to: CGPoint) {
    UIGraphicsBeginImageContext(imageView.frame.size)
    context = UIGraphicsGetCurrentContext()
    context?.setStrokeColor(UIColor(red: 0, green: 0, blue: 0, alpha: 1.0).cgColor)
    context?.setLineWidth(5.0)
    let currentRect = CGRect(x: from.x,
                             y: from.y,
                             width: to.x - from.x,
                             height: to.y - from.y)
    context?.addRect(currentRect)
    context?.drawPath(using: .stroke)
    context?.strokePath()
    imageView.image?.draw(in: self.imageView.frame)
    imageView.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}

I add the method to (touchMoved) it draws many rectangles

I add the method to (touchEnded) it draws one, but it does not appear when the user move the touch

screenshot

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        firstTouchLocation = touch.location(in: self.view)            
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        lastTouchLocation = touch.location(in: self.view)
        draw(from: firstTouchLocation, to: lastTouchLocation)
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        lastTouchLocation = touch.location(in: self.view)
        draw(from: firstTouchLocation, to: lastTouchLocation)
    }
}

I want to let the user extend the rectangle when touchMoved and draw when the touchEnded.

Rob
  • 415,655
  • 72
  • 787
  • 1,044

1 Answers1

1

You are replacing your image with a new image composed of the previous image plus a rectangle drawn over it. Rather than drawing the image from the image view, draw the original image.

Alternatively, you could render the the rectangle as a shape layer and just update that shape layer's path:

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    private let shapeLayer: CAShapeLayer = {
        let _shapeLayer = CAShapeLayer()
        _shapeLayer.fillColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor
        _shapeLayer.strokeColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor
        _shapeLayer.lineWidth = 3
        return _shapeLayer
    }()

    private var startPoint: CGPoint!

    override func viewDidLoad() {
        super.viewDidLoad()

        imageView.layer.addSublayer(shapeLayer)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        startPoint = touches.first?.location(in: imageView)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let startPoint = startPoint, let touch = touches.first else { return }

        let point: CGPoint

        if let predictedTouch = event?.predictedTouches(for: touch)?.last {
            point = predictedTouch.location(in: imageView)
        } else {
            point = touch.location(in: imageView)
        }

        updatePath(from: startPoint, to: point)
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let startPoint = startPoint, let touch = touches.first else { return }

        let point = touch.location(in: imageView)

        updatePath(from: startPoint, to: point)
        imageView.image = imageView.snapshot(afterScreenUpdates: true)
        shapeLayer.path = nil
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        shapeLayer.path = nil
    }

    private func updatePath(from startPoint: CGPoint, to point: CGPoint) {
        let size = CGSize(width: point.x - startPoint.x, height: point.y - startPoint.y)
        let rect = CGRect(origin: startPoint, size: size)
        shapeLayer.path = UIBezierPath(rect: rect).cgPath
    }

}

Where:

extension UIView {
    func snapshot(afterScreenUpdates: Bool = false) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
        drawHierarchy(in: bounds, afterScreenUpdates: afterScreenUpdates)
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}

This is not only simpler, but more efficient, too.

That yields:

enter image description here

By the way, I might suggest using predictive touches in touchesMoved. On a device (not the simulator) that can yield a slightly more responsive UI.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • where I can find information about "predictive touches" you know where I can find some tutorial or somethig? – Reinier Melian Aug 27 '17 at 16:03
  • 1
    @ReinierMelian - See WWDC 2015 [Advanced Touch Input on iOS](https://developer.apple.com/videos/play/wwdc2015/233/). Or just google "predictedTouches tutorial" and you'll see lots of links. – Rob Aug 27 '17 at 16:12
  • Thanks a lot.but it draws a rectangle and when a new touchBegan event it begins a new rectangle and deletes the previous one.I want to save a drawing after touch ends and start new one – Mohmed Showekh Aug 27 '17 at 16:21
  • @ReinierMelian - That's fine. Then do your "build new image" process at that point (in `touchesEnded`). Or add a new shape layer for the next gesture, leaving the old one there. The key point is to avoid altering the image during each `touchesMoved`. – Rob Aug 27 '17 at 16:32
  • @MohmedShowekh - See revised answer with `snapshot` extension on `UIView`. – Rob Aug 27 '17 at 17:33