I want to implement a lasso-like feature on a UIView, where a path is recorded as the finger moves. When the finger is lifted, the area is closed and displayed as a green closed region on the UIView. Then, a UIImage is generated where the closed area is white and the rest of the area is black.
When there are intersections, close the area based on the intersection points.
If there are no intersections, automatically connect the last point with the first point to close the area.
like the gif below
Can someone provide an example of how to implement this? Please use Swift on iOS
import UIKit
class DrawingAreaView: UIView {
private var path = UIBezierPath()
private var startPoint: CGPoint?
private var isPathClosed = false
override func draw(_ rect: CGRect) {
UIColor.clear.setFill()
UIRectFill(rect)
UIColor.black.setStroke()
path.stroke()
if isPathClosed {
UIColor.white.setFill()
path.fill()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
startPoint = touch.location(in: self)
path.move(to: startPoint!)
isPathClosed = false
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first, let startPoint = startPoint else { return }
let currentPoint = touch.location(in: self)
path.addLine(to: currentPoint)
self.setNeedsDisplay()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let startPoint = startPoint else { return }
// How to get the area and detecting Intersections, close path
self.setNeedsDisplay()
let maskImage = createMaskImage()
}
private func createMaskImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0)
if let context = UIGraphicsGetCurrentContext() {
UIColor.black.setFill()
context.fill(self.bounds)
UIColor.white.setFill()
path.fill()
}
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}





