我们如何使 Imageview 像梯形一样

How we make Imageview like Trapezium

我想制作类似梯形或四边形的图像enter image description here。并将图像设置为梯形。

 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
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
    }

用法:addDiamondMask(to: imageView)

假设您的 imageView IBOutlet 被命名为 imgView。然后您可以使用此代码为图像视图创建任何形状。

func createShape() {
    path = UIBezierPath()
    path.move(to: CGPoint(x: self.imgView.frame.width/2, y: 0.0))
    path.addLine(to: CGPoint(x: 0.0, y: self.imgView.frame.size.height))
    path.addLine(to: CGPoint(x: self.imgView.frame.size.width, y: self.imgView.frame.size.height))
    path.close()
    let mask = CAShapeLayer();
    mask.frame = imgView.bounds;
    mask.path = path.cgPath;
    imgView.layer.mask = mask;
}

此示例将创建一个三角形图像视图。