我试图创建一个自定义视图,顶部弯曲并在中间添加一个图像视图。

像这样:

ios - 波浪形(波浪形)顶部的自定义 View (快速)-LMLPHP

但是我不太习惯UIBezierPath,所以我很困惑。


  到目前为止,这是我所做的。


    class DemoView: UIView {

  var path: UIBezierPath!

  override init(frame: CGRect) {
      super.init(frame: frame)

      self.backgroundColor = UIColor.darkGray
    complexShape()
  }

  required init?(coder aDecoder: NSCoder) {
      super.init(coder: aDecoder)
    complexShape()
  }

    func complexShape() {
        path = UIBezierPath()
        path.move(to: CGPoint(x: 0.0, y: 0.0))
        path.addLine(to: CGPoint(x: self.frame.size.width/2 - 50.0, y: 0.0))
        path.addLine(to: CGPoint(x: self.frame.size.width/2, y: 0.0))
        path.addCurve(to: CGPoint(x: self.frame.size.width, y: 50.0),
                      controlPoint1: CGPoint(x: self.frame.size.width + 50.0, y: 25.0),
                      controlPoint2: CGPoint(x: self.frame.size.width - 150.0, y: 50.0))
        path.addLine(to: CGPoint(x: self.frame.size.width, y: self.frame.size.height))
        path.addLine(to: CGPoint(x: 0.0, y: self.frame.size.height))
        path.close()

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath


        self.layer.mask = shapeLayer
    }

}

extension CGFloat {
    func toRadians() -> CGFloat {
        return self * .pi / 180.0
    }
}

最佳答案

下面的方法可让您将背景波效果添加到另一个view。然后,您需要为前景广场做的就是添加另一个视图。播放常数以更改波形/高度。

func addWaveBackground(to view: UIView){
      let leftDrop:CGFloat = 0.4
      let rightDrop: CGFloat = 0.3
      let leftInflexionX: CGFloat = 0.4
      let leftInflexionY: CGFloat = 0.47
      let rightInflexionX: CGFloat = 0.6
      let rightInflexionY: CGFloat = 0.22

      let backView = UIView(frame: view.frame)
      backView.backgroundColor = .gray
      view.addSubview(backView)
      let backLayer = CAShapeLayer()
      let path = UIBezierPath()
      path.move(to: CGPoint(x: 0, y: 0))
      path.addLine(to: CGPoint(x:0, y: view.frame.height * leftDrop))
      path.addCurve(to: CGPoint(x:view.frame.width, y: view.frame.height * rightDrop),
                    controlPoint1: CGPoint(x: view.frame.width * leftInflexionX, y: view.frame.height * leftInflexionY),
                    controlPoint2: CGPoint(x: view.frame.width * rightInflexionX, y: view.frame.height * rightInflexionY))
      path.addLine(to: CGPoint(x:view.frame.width, y: 0))
      path.close()
      backLayer.fillColor = UIColor.blue.cgColor
      backLayer.path = path.cgPath
      backView.layer.addSublayer(backLayer)
   }


传递要添加波浪效果的视图(通常是VC的主视图)。

关于ios - 波浪形(波浪形)顶部的自定义 View (快速),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58915813/

10-11 11:29