I have created app where the user can take a picture and I would like to add a custom crop feature that works similar to Snapchats or PhotoShops magic wand tool. I found the code below from the Apple Developer Website which allows me to take the image captured and crop it into a CGRect
.
func cropImage(_ inputImage: UIImage, toRect cropRect: CGRect, viewWidth: CGFloat, viewHeight: CGFloat) -> UIImage?
{
let imageViewScale = max(inputImage.size.width / viewWidth,
inputImage.size.height / viewHeight)
// Scale cropRect to handle images larger than shown-on-screen size
let cropZone = CGRect(x:cropRect.origin.x * imageViewScale,
y:cropRect.origin.y * imageViewScale,
width:cropRect.size.width * imageViewScale,
height:cropRect.size.height * imageViewScale)
// Perform cropping in Core Graphics
guard let cutImageRef: CGImage = inputImage.cgImage?.cropping(to:cropZone)
else {
return nil
}
// Return image to UIImage
let croppedImage: UIImage = UIImage(cgImage: cutImageRef)
return croppedImage
}
Instead of using a GCRect
how can I draw around the object in the image and use that as the cropZone
? Any help would be greatly appreciated.
CodePudding user response:
What you ask is a fairly complex task, and beyond the scope of an SO question. I can give you an outline of what you'd need to do:
Implement a drawing method that lets the user draw on top of the image and create a closed CGPath/UIBezierPath from that drawing
Install that path into the image view's layer's mask property. That will hide the parts of the image outside
Find the bounding rectangle of the shape the user draws, and crop to that as you're doing above.