迅速将UIView边框变成渐变颜色

时间:2019-09-25 12:41:53

标签: swift

我想在UIView上创建渐变边框。

以下代码可以为Box1视图生成实体。

我发现的所有内容都不允许我将frameColor更改为渐变。

    var frameColor = UIColor.red.cgColor

    var leftBorder = CALayer()
    leftBorder.frame = CGRect(x: 0.0, y: 0, width: 1, height: box1.frame.size.height )
    leftBorder.backgroundColor = frameColor

我正在使用Swift 5和Xcode 11。

谢谢。

2 个答案:

答案 0 :(得分:2)

尝试以下扩展名

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
}

}

用法

self.borderView.setGradientBorder(width: 5.0, colors: [UIColor.red , UIColor.blue])

enter image description here

我希望这能满足您的要求。

https://medium.com/@kushal0409/gradient-button-3dc8ef763039

答案 1 :(得分:0)

目前尚无现成的方法,但是您可以自己构建。

在我的头顶上,这种方法可能看起来像这样:

  • 创建一个CAGradientLayer并将其设置为绘制渐变为

  • 创建一个CAShapeLayer,其中包含一个空矩形, 框架。

  • 添加形状图层作为渐变图层的蒙版。

  • 将渐变层添加为视图的子层 内容层。