Hey Im construct a cropping doc app.
Im getting the picture transformed from CIImage to UIImage from the digital camera.
As soon as its arrives in my SwiftUI View, I draw a cropping view above.
Then I crop the view utilizing UIBezierPath.
One thing within the cropping is one way or the other mistaken as a result of the form is appropriate however the content material of the image shouldn’t be.
Right here is the struct holding my factors:
struct PathPoint {
var topLeft: CGPoint
var topRight: CGPoint
var bottomLeft: CGPoint
var bottomRight: CGPoint
init(topLeft: CGPoint = .zero, topRight: CGPoint = .zero, bottomLeft: CGPoint = .zero, bottomRight: CGPoint = .zero) {
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = bottomRight
}
func createBezierPath() -> UIBezierPath {
let path = UIBezierPath()
path.transfer(to: topLeft)
path.addLine(to: topRight)
path.addLine(to: bottomRight)
path.addLine(to: bottomLeft)
path.shut() // Shut the trail to kind a rectangle
return path
}
func createCGPath() -> CGPath {
createBezierPath().cgPath
}
}
Right here is place the place the cropping code :
func imageByApplyingClippingBezierPath(_ path: UIBezierPath) -> UIImage? {
guard let maskedImage = imageByApplyingMaskingBezierPath(path),
let cgImage = maskedImage.cgImage else { return nil }
guard let cropped = cgImage.cropping(to: path.bounds) else {
print(#perform, "couldn't crop for bounds (path.bounds)")
return nil
}
let croppedImage = UIImage(cgImage: cropped)
return croppedImage
}
func imageByApplyingMaskingBezierPath(_ path: UIBezierPath) -> UIImage? {
UIGraphicsBeginImageContext(dimension)
let context = UIGraphicsGetCurrentContext()!
context.saveGState()
path.addClip()
draw(in: CGRect(x: 0, y: 0, width: dimension.width, peak: dimension.peak))
guard let maskedImage = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
context.restoreGState()
UIGraphicsEndImageContext()
return maskedImage
}