티스토리 뷰

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)

    }

}

func removeGradientBorder() {

    self.gradientBorderLayer()?.removeFromSuperlayer()

}

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

}

}

 

 

사용법

ex) self.setGradientBorder(width: 2.0, colors: [UIColor.systemGray2,UIColor.systemGray5])

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함