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

问题描述 投票:16回答:4

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

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

ios image camera uiimagepickercontroller crop
4个回答
27
投票

使用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)

功能示例:

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属性定义将被裁剪的图像内的“裁剪矩形”。


10
投票

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

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


7
投票

https://github.com/myang-git/iOS-Image-Crop-View做的就是你想要的东西..

希望这可以帮助。


0
投票

如果您在裁剪图像后遇到旋转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
© www.soinside.com 2019 - 2024. All rights reserved.