gpt4 book ai didi

ios - Swift - 使用 UIBezierPath 裁剪图像

转载 作者:可可西里 更新时间:2023-11-01 01:57:52 37 4
gpt4 key购买 nike

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

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/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com