Search code examples
swiftcalayer

How we make Imageview like Trapezium


I want to make image like trapezium or Quadilateral enter image description here. And set Image on trapezium.

 let path = UIBezierPath()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: view.bounds.width, y: 0))
        path.addLine(to: CGPoint(x: self.view.bounds.width, y: self.view.bounds.height/2 - 60)) // 50
        path.addLine(to: CGPoint(x: 0, y: view.bounds.size.width - 85)) // 80
        path.close()

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath
        shapeLayer.fillColor = UIColor.black.cgColor
        shapeLayer.strokeColor = UIColor.black.cgColor
        view.layer.mask = shapeLayer

Solution

  • func addDiamondMask(to view: UIView)
            {
    
            let path = UIBezierPath()
            path.move(to: CGPoint(x: 0, y: 0))
            path.addLine(to: CGPoint(x: view.bounds.width, y: 0))
            path.addLine(to: CGPoint(x: self.view.bounds.width, y: self.view.bounds.height/2 - 60))
            path.addLine(to: CGPoint(x: 0, y: view.bounds.size.width - 85)) 
            path.close()
    
            let shapeLayer = CAShapeLayer()
            shapeLayer.path = path.cgPath
            shapeLayer.fillColor = UIColor.white.cgColor
            shapeLayer.strokeColor = UIColor.gray.cgColor
            view.layer.mask = shapeLayer
        }
    

    usage : addDiamondMask(to: imageView)