这是基于 UIBezierPath 从图像中获取剪辑的 Swift 代码,它的实现速度非常快。如果图像已经显示在屏幕上,则此方法有效,通常是这种情况。生成的图像将具有透明背景,这是大多数人在剪辑照片图像的一部分时想要的。您可以在本地使用生成的剪切图像,因为您将在我称为 imageWithTransparentBackground 的 UIImage 对象中拥有它。这个非常简单的代码还向您展示了如何将图像保存到相机胶卷,以及如何将其直接放入粘贴板,以便用户可以将该图像直接粘贴到文本消息中,将其粘贴到 Notes、电子邮件等中。请注意,为了将图像写入相机胶卷,您需要编辑 info.plist 并提供“隐私 - 照片库使用说明”的原因
import Photos // Needed if you save to the camera roll
为剪辑提供 UIBezierPath。这是我的声明。
let clipPath = UIBezierPath()
使用某些命令组合使用您自己的逻辑填充 clipPath。以下是我在绘图逻辑中使用的一些。为 aPointOnScreen 等提供 CGPoint 等效项 构建相对于主屏幕的路径,因为 self.view 是这个应用程序的 ViewController(对于此代码),并且 self.view.layer 通过 clipPath 呈现。
clipPath.move(to: aPointOnScreen)
clipPath.addLine(to: otherPointOnScreen)
clipPath.addLine(to: someOtherPointOnScreen)
clipPath.close()
此逻辑使用所有设备屏幕作为上下文大小。为此声明了一个 CGSize。 fullScreenX 和 fullScreenY 是我已经捕获设备宽度和高度的变量。如果您正在剪辑的照片已经放大并且在整个屏幕上显示的尺寸足够大,那就太好了。所见即所得。
let mainScreenSize = CGSize(width: fullScreenX, height: fullScreenY)
// Get an empty context
UIGraphicsBeginImageContext(mainScreenSize)
// Specify the clip path
clipPath.addClip()
// Render through the clip path from the whole of the screen.
self.view.layer.render(in: UIGraphicsGetCurrentContext()!)
// Get the clipped image from the context
let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
// Done with the context, so end it.
UIGraphicsEndImageContext()
// The PNG data has the alpha channel for the transparent background
let imageData = image.pngData()
// Below is the local UIImage to use within your code
let imageWithTransparentBackground = UIImage.init(data: imageData!)
// Make the image available to the pasteboard.
UIPasteboard.general.image = imageWithTransparentBackground
// Save the image to the camera roll.
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAsset(from: imageWithTransparentBackground!)
}, completionHandler: { success, error in
if success {
//
}
else if let error = error {
//
}
else {
//
}
})