Setting multiple borders on UIView

后端 未结 5 484
庸人自扰
庸人自扰 2021-01-13 17:39

As I cannot find any questions/answers for this, I imagine it is not possible.

Is there anyway to set multiple borders on a UIView.

I am curren

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-13 18:35

    You can insert two layers of different widths using this extension:

    extension CALayer {
        func addGradientBorder(colors:[UIColor],width:CGFloat = 1) {
            let gradientLayer = CAGradientLayer()
            gradientLayer.frame =  CGRect(origin: CGPoint.zero, size: self.bounds.size)
            gradientLayer.startPoint = CGPoint(x:0.0, y:0.0)
            gradientLayer.endPoint = CGPoint(x:1.0,y:1.0)
            gradientLayer.colors = colors.map({$0.cgColor})
    
            let shapeLayer = CAShapeLayer()
            shapeLayer.lineWidth = width
            shapeLayer.path = UIBezierPath(rect: self.bounds).cgPath
            shapeLayer.fillColor = nil
            shapeLayer.strokeColor = UIColor.red.cgColor
            gradientLayer.mask = shapeLayer
    
            self.addSublayer(gradientLayer)
        }
    }
    

    Use this with different widths/colors to get the desired effect:

    yourView.layer.addGradientBorder(colors:[UIColor.black,UIColor.black] , width: 20)
    yourView.layer.addGradientBorder(colors:[UIColor.white,UIColor.white] , width: 10)
    

    Output looks like the following image with outer white border and inner black border:

提交回复
热议问题