在UIView容器中添加bezierpath

时间:2017-01-05 01:14:58

标签: ios swift uiview uibezierpath

我正在尝试在UIView容器内部(底部)添加一个bezierpath(三角形)但是我似乎无法正确理解UIView容器。我得到了一个结果(似乎在容器视图的左侧显示了三角形的条带):enter image description here

我想输出如下:

enter image description here

到目前为止,这是我的代码:

   // adding container to add image
        self.topContainer.backgroundColor = UIColor(red: 49/255, green:  207/255, blue: 203/255, alpha: 1)
        //        self.topContainer.backgroundColor = UIColor.white
        self.topContainer.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(self.topContainer)


        self.topContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        self.topContainer.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.55).isActive = true
        self.topContainer.widthAnchor.constraint(equalTo: view.widthAnchor).isActive =  true

        let bezierPath = UIBezierPath()                
        bezierPath.move(to: CGPoint(x: 0, y: self.topContainer.frame.size.height))
        bezierPath.addLine(to: CGPoint(x: self.topContainer.frame.size.width, y: 222))
        bezierPath.addLine(to: CGPoint(x: self.topContainer.frame.size.width, y: self.topContainer.frame.size.height))
        bezierPath.addLine(to: CGPoint(x: 0, y: self.topContainer.frame.size.height))

        UIColor.white.setFill()
        bezierPath.fill()
        bezierPath.lineWidth = 1
        bezierPath.close()

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = bezierPath.cgPath
        shapeLayer.lineWidth = 2.0
        shapeLayer.strokeColor = UIColor.white.cgColor
        shapeLayer.fillColor = UIColor.white.cgColor
        self.topContainer.layer.addSublayer(shapeLayer)

1 个答案:

答案 0 :(得分:0)

您显然是在视图控制器的junit中执行此代码。你应该:

  • 删除@AfterClassviewDidLoad代码。只有在图形上下文(例如UIColor.white.setFill()的{​​{1}}方法或path.fill()内)中绘制时才有意义。只需构造draw并将其添加到视图/图层层次结构中,操作系统将为您绘制/填充它。

  • 继续在UIView中创建和配置UIGraphicsBegin/EndImageContext,但移动CAShapeLayer的创建和CAShapeLayer的设置{{} 1}}到视图控制器的viewDidLayoutSubviews方法。在viewDidLoad期间,视图的UIBezierPath通常是未知的,并且肯定容易被更改(通过约束或自动调整掩码)。在调用CAShapeLayer时,path已正确配置(如果主视图的frame发生更改,将再次调用。)