how to make a gradient border of UIView?

后端 未结 6 1107
遇见更好的自我
遇见更好的自我 2020-12-28 17:37

I want to make a gradient border of view like the following picture:

\"Image\"

but I don\'t know how d

6条回答
  •  执笔经年
    2020-12-28 18:17

    Here is another solution that is working on swift 4

    import UIKit
    
    public extension UIView {
    
        private static let kLayerNameGradientBorder = "GradientBorderLayer"
    
        func setGradientBorder(
            width: CGFloat,
            colors: [UIColor],
            startPoint: CGPoint = CGPoint(x: 0.5, y: 0),
            endPoint: CGPoint = CGPoint(x: 0.5, y: 1)
        ) {
            let existedBorder = gradientBorderLayer()
            let border = existedBorder ?? CAGradientLayer()
            border.frame = bounds
            border.colors = colors.map { return $0.cgColor }
            border.startPoint = startPoint
            border.endPoint = endPoint
    
            let mask = CAShapeLayer()
            mask.path = UIBezierPath(roundedRect: bounds, cornerRadius: 0).cgPath
            mask.fillColor = UIColor.clear.cgColor
            mask.strokeColor = UIColor.white.cgColor
            mask.lineWidth = width
    
            border.mask = mask
    
            let exists = existedBorder != nil
            if !exists {
                layer.addSublayer(border)
            }
        }
    
    
        private func gradientBorderLayer() -> CAGradientLayer? {
            let borderLayers = layer.sublayers?.filter { return $0.name == UIView.kLayerNameGradientBorder }
            if borderLayers?.count ?? 0 > 1 {
                fatalError()
            }
            return borderLayers?.first as? CAGradientLayer
        }
    
    }
    

    How to use:

    view.setGradientBorder(width: 10, colors: [UIColor(red: 47, green: 198, blue: 176), UIColor(red: 67, green: 210, blue: 128)])

提交回复
热议问题