我正在尝试根据给定的 UIBezierPath
裁剪 UIImage
,但生成的图像保留了原始形状和大小。我希望形状和大小类似于路径,即新图像的可见内容。
看看下面这个例子:
以下是我用来屏蔽给定路径的图像的代码:
func imageByApplyingClippingBezierPath(_ path: UIBezierPath) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(
width: size.width,
height: size.height
), false, 0.0)
let context = UIGraphicsGetCurrentContext()!
context.saveGState()
path.addClip()
draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
context.restoreGState()
UIGraphicsEndImageContext()
return newImage
}
一种解决方案是在蒙版后裁剪图像,但理想情况下,我希望一次性尽可能简单高效地完成此操作。
任何解决方案/提示将不胜感激。
最佳答案
感谢Rob我能够使用 CGImage
的 cropping(to:)
方法实现解决方案。
这是一个两步过程,首先我使用给定的路径遮盖图像,然后使用路径的边界裁剪结果。
以下是我实现剪辑 UIBezierPath
UIImage
扩展的最终工作源代码:
extension UIImage {
func imageByApplyingClippingBezierPath(_ path: UIBezierPath) -> UIImage {
// Mask image using path
let maskedImage = imageByApplyingMaskingBezierPath(path)
// Crop image to frame of path
let croppedImage = UIImage(cgImage: maskedImage.cgImage!.cropping(to: path.bounds)!)
return croppedImage
}
func imageByApplyingMaskingBezierPath(_ path: UIBezierPath) -> UIImage {
// Define graphic context (canvas) to paint on
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()!
context.saveGState()
// Set the clipping mask
path.addClip()
draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let maskedImage = UIGraphicsGetImageFromCurrentImageContext()!
// Restore previous drawing context
context.restoreGState()
UIGraphicsEndImageContext()
return maskedImage
}
}
关于ios - 将 UIImage 剪辑到 UIBezierPath(不屏蔽),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40815247/