代码之家  ›  专栏  ›  技术社区  ›  Curnelious

根据UIBezier剪切UIImageView?

  •  1
  • Curnelious  · 技术社区  · 8 年前

    我有一个 UIImageView ,具有某种图像。 我还有一个 UIBezierPath 以某种奇怪的形状。 我想把图像剪切成那个形状,并在那个形状中返回一个新图像。

    enter image description here

    形式如下:

    func getCut(bezier:UIBezierPath, image:UIImageView)->UIImageView
    
    3 回复  |  直到 8 年前
        1
  •  3
  •   Willjay    8 年前

    您可以使用 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
        }
    }
    
        2
  •  1
  •   Josh Homann    8 年前

    使用UIGraphicsImageRenderer制作带有剪裁路径的图像。这里是一个操场:

    import PlaygroundSupport
    import UIKit
    
    let imageToCrop = UIImage(named: "test.jpg")!
    let size = imageToCrop.size
    let cutImage = UIGraphicsImageRenderer(size: size).image { imageContext in
        let context = imageContext.cgContext
        let clippingPath = UIBezierPath(ovalIn: CGRect(origin: .zero, size: size)).cgPath
        context.addPath(clippingPath)
        context.clip(using: .evenOdd)
        imageToCrop.draw(at: .zero)
    }
    
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
    imageView.image = cutImage
    PlaygroundPage.current.liveView = imageView
    
        3
  •  0
  •   Sneha    8 年前

    您可以使用 CAShapeLayer 用于塑造图像&然后从该形状获取图像。。。

    UIGraphicsBeginImageContext(imgView.bounds.size);
    [imgView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *mainImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    非常感谢。

    引用自 here ..