如何使用Swift选择图像的一部分,裁剪并保存?

我正在尝试使用Swift创建一个iOS应用程序来捕获图像,并让用户保存图像的选定部分。 在许多基于凸轮的应用程序中,我注意到提供了一个矩形框架,让用户选择所需的部分。 这涉及滑动矩形的边缘或移动角落以适合所需的区域。

你能否指导我如何实现这个可移动的矩形以及如何只保存那部分图像?

使用Swift 3

可以使用CoreGraphics的 CGImages完成图像裁剪。

获取像这样的UIImage的CGImage版本:

// cgImage is an attribute of UIImage let cgImage = image.cgImage 

CGImage对象有一个方法裁剪(到:CGRect)进行裁剪:

 let croppedCGImage: CGImage = cgImage.cropping(to: toRect) 

最后,从CGImage转换回UIImage

 let uiImage = UIImage(cgImage: croppedCGImage) 

function示例:

 func cropImage(image: UIImage, toRect: CGRect) -> UIImage? { // Cropping is available trhough CGGraphics let cgImage :CGImage! = image.cgImage let croppedCGImage: CGImage! = cgImage.cropping(to: toRect) return UIImage(cgImage: croppedCGImage) } 

裁剪的CGRect属性定义将被裁剪的图像内的“裁剪矩形”。

找到了一个解决方案。 这次是在斯威夫特。 该解决方案看起来很优雅,相对于其他此类解决方案的代码用较少的行编写。

这里是.. https://github.com/DuncanMC/CropImg感谢Duncan Champney在github上提供他的作品。

如果您在裁剪图像后遇到旋转90等问题,请尝试此操作。
存储原始图像比例和方向属性以供以后使用

 let imgOrientation = image?.imageOrientation let imgScale = image?.scale 

从UIImage获取CGImage:

 let cgImage = image.cgImage 

传递要裁剪的cropArea(CGRect)区域(如果您使用的是imageView.image,您已找到比例并执行数学查找cgRect)如果需要,请添加以下代码

 let croppedCGImage = cgImage.cropping(to: cropArea) let coreImage = CIImage(cgImage: croppedCGImage!) 

需要渲染图像的上下文(如果您多次执行,请查看https://developer.apple.com/documentation/coreimage/cicontext )这样您可以设置我们在第一行创建的比例和方向,这样图像不要旋转90

 let ciContext = CIContext(options: nil) let filteredImageRef = ciContext.createCGImage(coreImage, from: coreImage.extent) let finalImage = UIImage(cgImage:filteredImageRef!, scale:imgScale!, orientation:imgOrientation!) imageView.image = finalImage