swift - 根据UIBezier切割UIImageView?

标签 swift uiimageview uibezierpath

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

enter image description here

形式为:

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

最佳答案

您可以使用mask来执行此操作。这是一个简单的示例。

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/

相关文章:

Swift:如何创建附加在导航栏下方的辅助栏?

ios - UIPageViewController 中包含的 ViewController 的委托(delegate)为零

swift - 为什么在 Swift 中通过 Selector 调用时不考虑函数的默认参数?

swift - 基于 swift 2 中的另一个枚举创建一个枚举

swift - 如何在 Swift 中通过 ImageView 创建自定义文本字段

ios - 具有多个路径的UIBezierPath不连接具有斜角类型的线

ios - 圆笔触宽度更改动画而不更改圆半径

ipad - 带有许多 UIImageViews 的 UIScrollView - 内存管理

ios - iPad 仅在设备上扭曲 UIImageView

ios - 在 Objective-C 中发布带有两个端点的绘图线