我们如何使Imageview像Trapezium

时间:2017-12-01 09:28:25

标签: swift calayer

我想制作像梯形或四边形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

2 个答案:

答案 0 :(得分:0)

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)

答案 1 :(得分:0)

假设您的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;
}

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