我想从图像中裁剪bezier路径。由于某些原因,图像仍然是未剪裁的。我如何定位路径,使其被正确剪切?
extension UIImage {
func imageByApplyingMaskingBezierPath(_ path: UIBezierPath, _ pathFrame: CGFrame) -> UIImage {
    UIGraphicsBeginImageContext(self.size)
    let context = UIGraphicsGetCurrentContext()!
    context.saveGState()
    path.addClip()
    draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
    let maskedImage = UIGraphicsGetImageFromCurrentImageContext()!
    context.restoreGState()
    UIGraphicsEndImageContext()
    return maskedImage
}
}

发布于 2018-04-16 17:05:37
您需要将path.cgPath添加到当前上下文中,还需要删除context.saveGState()和context.restoreGState()
使用此代码
func imageByApplyingMaskingBezierPath(_ path: UIBezierPath, _ pathFrame: CGRect) -> UIImage {
            UIGraphicsBeginImageContext(self.size)
            let context = UIGraphicsGetCurrentContext()!
            context.addPath(path.cgPath)
            context.clip()
            draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
            let maskedImage = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            return maskedImage
        }使用it的
let testPath = UIBezierPath()
testPath.move(to: CGPoint(x: self.imageView.frame.width / 2, y: self.imageView.frame.height))
testPath.addLine(to: CGPoint(x: 0, y: 0))
testPath.addLine(to: CGPoint(x: self.imageView.frame.width, y: 0))
testPath.close()
self.imageView.image = UIImage(named:"Image")?.imageByApplyingMaskingBezierPath(testPath, self.imageView.frame)结果

https://stackoverflow.com/questions/49853122
复制相似问题