我正在尝试剪辑UIImage
基于给定的UIBezierPath
,但生成的图像保留原始形状和大小。我希望形状和大小类似于路径,即新图像的可见内容。
看看下面的例子:
以下是我用来屏蔽给定路径的图像的代码:
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 https://stackoverflow.com/users/1271826/rob我能够使用以下方法实现解决方案cropping(to:)
的方法CGImage
.
这是一个两步过程,首先我使用给定的路径屏蔽图像,然后使用路径的边界裁剪结果。
以下是我用于实现的最终工作源代码clipping 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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)