SwiftUI中UIBezierPath裁剪Image位置偏移问题求助
文档裁剪应用的内容偏移问题
我正在开发一款文档裁剪应用,流程是从相机获取图像,将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 }
示意图
- 裁剪操作示意图:

- 裁剪结果图:

内容的提问来源于stack exchange,提问作者Ruben Mim
相关产品推荐
相关产品推荐

