How to draw CALayer border around its mask?

Fahri Azimov picture Fahri Azimov · Apr 5, 2013 · Viewed 14k times · Source

So, I have a CALayer, which has a mask & I want to add border around this layer's mask. For example, I have set triangle mask to the layer and I want to have border around that layer.

Can anyone please help me to solve this problem?

Answer

iluvatar_GR picture iluvatar_GR · Jun 30, 2017

Swift 4

enter image description here

class CustomView: UIView {
override func draw(_ rect: CGRect) {
    super.draw(rect)
    self.backgroundColor = UIColor.black

    //setup path for mask and border
    let halfHeight = self.bounds.height * 0.5
    let maskPath = UIBezierPath(roundedRect: self.bounds,
                                byRoundingCorners: [.topLeft, .bottomRight],
                                cornerRadii: CGSize(width: halfHeight,
                                                    height: halfHeight))

    //setup MASK
    self.layer.mask = nil;
    let maskLayer = CAShapeLayer()
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.cgPath
    self.layer.mask = maskLayer

    //setup Border for Mask
    let borderLayer = CAShapeLayer()
    borderLayer.path = maskPath.cgPath
    borderLayer.lineWidth = 25
    borderLayer.strokeColor = UIColor.red.cgColor
    borderLayer.fillColor = UIColor.clear.cgColor
    borderLayer.frame = self.bounds
    self.layer.addSublayer(borderLayer)
}