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 b
If you subclass CALayer
, you could instantiate it with the mask you want, and also override layoutSubLayers
to include the border you want. This will work for all masks and should be the new accepted answer.
Could do this a couple ways. Below Ill do it by using the path
of the given mask, and assigning that to class property to be used for constructing the new border in layoutSubLayers
. There is potential that this method could be called multiple times, so I also set a boolean to track this. (Could also assign the border as a class property, and remove/re-add each time. For now I use bool check.
Swift 3:
class CustomLayer: CALayer {
private var path: CGPath?
private var borderSet: Bool = false
init(maskLayer: CAShapeLayer) {
super.init()
self.path = maskLayer.path
self.frame = maskLayer.frame
self.bounds = maskLayer.bounds
self.mask = maskLayer
}
override func layoutSublayers() {
if(!borderSet) {
self.borderSet = true
let newBorder = CAShapeLayer()
newBorder.lineWidth = 12
newBorder.path = self.path
newBorder.strokeColor = UIColor.black.cgColor
newBorder.fillColor = nil
self.addSublayer(newBorder)
}
}
required override init(layer: Any) {
super.init(layer: layer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}