如何使用bezier路径剪辑UIView?

时间:2018-03-19 11:26:59

标签: ios uibezierpath

我不完全确定UIBezierPath应该如何运作。

我在屏幕中间添加了一个简单的UIView,我想通过在其图层中添加一个遮罩来剪切它。我试过这个,以为我在视图中间得到了类似于losange的东西:

override func viewDidLoad() {
    super.viewDidLoad()
    viewToClip.backgroundColor = .white
    let bezierPath = UIBezierPath()
    bezierPath.move(to: viewToClip.center)
    bezierPath.addLine(to: CGPoint(x: viewToClip.center.x - 5, y: viewToClip.center.y))
    bezierPath.addLine(to: CGPoint(x: viewToClip.center.x, y: viewToClip.center.y - 5))
    bezierPath.addLine(to: CGPoint(x: viewToClip.center.x + 5, y: viewToClip.center.y))
    bezierPath.addLine(to: CGPoint(x: viewToClip.center.x, y: viewToClip.center.y + 5))
    bezierPath.close()
    let testLayer = CAShapeLayer()
    testLayer.path = bezierPath.cgPath
    viewToClip.layer.mask = testLayer
}

但不是这样,视图就会从屏幕上消失。我做错了什么?

感谢您的帮助。

1 个答案:

答案 0 :(得分:-2)

你能试试吗

import UIKit

class bb: UIView {

   var once:Bool = true 

     override func draw(_ rect: CGRect) {

      if(once)
      {
        once = false
        self.backgroundColor = .white
        let bezierPath = UIBezierPath()
        let cen = CGPoint.init(x: self.bounds.size.width/2, y: self.bounds.size.height/2)
        bezierPath.move(to: cen)
        bezierPath.addLine(to: CGPoint(x: cen.x - 5, y: cen.y))
        bezierPath.addLine(to: CGPoint(x: cen.x, y: cen.y - 5))
        bezierPath.addLine(to: CGPoint(x: cen.x + 5, y: cen.y))
        bezierPath.addLine(to: CGPoint(x: cen.x, y: cen.y + 5))
        bezierPath.close()
        let testLayer = CAShapeLayer()
        testLayer.path = bezierPath.cgPath
        testLayer.lineWidth = 1.0

        testLayer.strokeColor = UIColor.blue.cgColor
        testLayer.fillColor = UIColor.green.cgColor
        self.layer.addSublayer(testLayer)
      }        

}