gpt4 book ai didi

swift - 根据 UIBezier 切割 UIImageView?

转载 作者:搜寻专家 更新时间:2023-11-01 07:06:36 28 4
gpt4 key购买 nike

我有一个 UIImageView,带有特定的图像。我还有一个形状奇怪的 UIBezierPath。我想将图像剪切成该形状并返回该形状的新图像。

enter image description here

形式为:

func getCut(bezier:UIBezierPath, image:UIImageView)->UIImageView

最佳答案

您可以使用掩码 来做到这一点。这是一个简单的例子。

class ViewController: UIViewController {

var path: UIBezierPath!
var touchPoint: CGPoint!
var startPoint: CGPoint!

var imageView = UIImageView(image: #imageLiteral(resourceName: "IMG_0715"))

override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(imageView)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
startPoint = touch.location(in: view)
path = UIBezierPath()
path.move(to: startPoint)
}
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
touchPoint = touch.location(in: view)
}

path.addLine(to: touchPoint)
startPoint = touchPoint

}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
cut()
}

private func cut() {
guard let path = path else { return }
imageView = imageView.getCut(with: path)
}

}

extension UIImageView {
func getCut(with bezier: UIBezierPath) -> UIImageView {

let shapeLayer = CAShapeLayer()
shapeLayer.path = bezier.cgPath

self.layer.mask = shapeLayer

return self
}
}

关于swift - 根据 UIBezier 切割 UIImageView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47667946/

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