ios - Swift - 使用 UIBezierPath 裁剪图像

标签 ios swift uiimage core-graphics uibezierpath

我想从图像中剪下一条贝塞尔曲线路径。出于某种原因,图像保持未剪裁状态。我如何定位路径以便正确切割?

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
}

}

example

最佳答案

您需要将您的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
        }

使用它

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)

结果

enter image description here

关于ios - Swift - 使用 UIBezierPath 裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49853122/

相关文章:

ios - 我试图通过协议(protocol)从不同的 UIViewController 调用一个函数,但我在委托(delegate)上得到的是 nil - 这里可能是什么情况?

ios - 如何在 iOS 上的 GPU 上将 3D SceneKit 内容合成到视频帧上?

Swift 通用约束无法转换值

ios - Swift 3-AVAudioPlayer无法播放声音

swift - 我想在另一个 View Controller 上添加一个 View Controller 5 秒?

ios - UITableViewCell ios 的错误

iphone - 如何从 MFMailComposer 的收件人地址中获取电子邮件地址

ios - 带有 CIFilters 的 CAShapeLayer

ios - 如何在 Objective-C 的 AlertView 中通过 http url 显示图像?

快速变色显示不同颜色