Я получаю изображение, конвертируемое из CIImage в UIImage с камеры.
Как только оно поступает в мое представление SwiftUI, я рисую изображение обрезки выше.
Затем я обрезаю изображение с помощью UIBezierPath.
Что-то при обрезке не так, потому что форма правильная, а содержимое изображения — нет.
Вот структура, в которой хранятся мои очки:
Код: Выделить всё
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.move(to: topLeft)
path.addLine(to: topRight)
path.addLine(to: bottomRight)
path.addLine(to: bottomLeft)
path.close() // Close the path to form a rectangle
return path
}
func createCGPath() -> CGPath {
createBezierPath().cgPath
}
}
Код: Выделить всё
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(#function, "could not crop for bounds \(path.bounds)")
return nil
}
let croppedImage = UIImage(cgImage: cropped)
return croppedImage
}
func imageByApplyingMaskingBezierPath(_ path: UIBezierPath) -> UIImage? {
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()!
context.saveGState()
path.addClip()
draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
guard let maskedImage = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
context.restoreGState()
UIGraphicsEndImageContext()
return maskedImage
}


Подробнее здесь: https://stackoverflow.com/questions/789 ... d-location