Stroke masked CALayer in iOS

后端 未结 2 1682
抹茶落季
抹茶落季 2021-02-05 18:06

I\'m trying to create a label (or any other view for that matter) with one rounded corner and a stroke/border. I can achieve the former using the following code:



        
2条回答
  •  误落风尘
    2021-02-05 18:45

    If you subclass CALayer, you could instantiate it with the mask you want, and also override layoutSubLayers to include the border you want on that mask.

    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() {
    
            let newBorder = CAShapeLayer()
    
            newBorder.lineWidth = 12
            newBorder.path = self.path
            newBorder.strokeColor = UIColor.black.cgColor
            newBorder.fillColor = nil
    
    
            if(!borderSet) {
                self.addSublayer(newBorder)
                self.borderSet = true
            }
    
        }
    
        required override init(layer: Any) {
            super.init(layer: layer)
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    

提交回复
热议问题