Search code examples
iosswiftcalayeruibezierpathcashapelayer

How to set CAShapeLayer 's strokeColor in swift


I want draw diagonal view.

This is my code.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let path = UIBezierPath()
    path.move(to: CGPoint.zero)
    path.addLine(to: CGPoint(x: 50, y: 50))

    let view = UIView(frame: CGRect(x: 100, y: 100, width: 50, height: 50))
    view.backgroundColor = UIColor.blue

    let mask = CAShapeLayer()
    mask.frame = view.bounds
    mask.path = path.cgPath
    mask.strokeColor = UIColor.orange.cgColor
    mask.lineWidth = 25

    view.layer.mask = mask

    self.view.addSubview(view)
}

I set strokeColor to orange. But color is blue backgroundColor

Why does this happen?


Solution

  • Here is the code snippet:

            let path = UIBezierPath()
            path.move(to: CGPoint.zero)
            path.addLine(to: CGPoint(x: 50, y: 50))
    
            let view = UIView(frame: CGRect(x: 100, y: 100, width: 50, height: 50))
            view.backgroundColor = UIColor.green
    
            let diagonal = CAShapeLayer()
            diagonal.frame = view.bounds
            diagonal.path = path.cgPath
            diagonal.strokeColor = UIColor.orange.cgColor
            diagonal.lineWidth = 15
            diagonal.backgroundColor = UIColor.blue.cgColor
            // view.layer.mask = mask
    
            view.layer.addSublayer(diagonal)
    
            self.view.addSubview(view)
    

    This results in:

    enter image description here