How to draw CALayer border around its mask?

后端 未结 6 1451
谎友^
谎友^ 2021-02-07 09:39

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

6条回答
  •  清歌不尽
    2021-02-07 10:09

    Swift 4

    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)
    }
    

提交回复
热议问题