使用径向渐变作为UIView的扩展

时间:2019-03-04 21:27:49

标签: ios swift calayer cagradientlayer

我的目标是为UIView进行径向渐变扩展。这是我的代码:

extension UIView {
    func drawRadialGradient() {
        let colors = Colors.gradientColors as CFArray
        let gradient = CGGradient(colorsSpace: nil, colors: colors, locations: nil)
        guard let gradientValue = gradient  else{ return }
        let endRadius: CGFloat? = max(frame.width, frame.height) / 2
        guard let endRadiusValue = endRadius else{ return }
        let bottomcenterCoordinates = CGPoint(x: frame.width / 2, y: frame.height)
        let getCurrentContext = UIGraphicsGetCurrentContext()
        guard let currentContext = getCurrentContext else{ return }
        currentContext.drawRadialGradient(gradientValue, startCenter: bottomcenterCoordinates, startRadius: 0.0, endCenter: bottomcenterCoordinates, endRadius: endRadiusValue, options: CGGradientDrawingOptions.drawsAfterEndLocation)
        let radialGradientLayer = CALayer(layer: currentContext)
        radialGradientLayer.frame = bounds
        radialGradientLayer.masksToBounds = true
        self.layer.insertSublayer(radialGradientLayer, at: 1)
    }
}

当我在viewDidLoad()或viewWillAppear()中调用此函数时,编译器不包含错误和警告,该函数无法正常工作。我这样称呼它:

override func viewDidLoad() {
    super.viewDidLoad()
    view.drawRadialGradient()
}

例如,我创建了一个扩展函数,用于在UIView上绘制线性渐变,并且它可以正常工作,我将其称为径向渐变函数:

func drawLinearGradient() {
    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = self.frame
    gradientLayer.colors = Colors.gradientColors
    gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.95)
    gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.05)
    self.layer.insertSublayer(gradientLayer, at: 0)
}

对于颜色,我创建了一个结构:

struct Colors {
    static let firstColor = colorPicker(red: 70, green: 183, blue: 0)
    static let secondColor = colorPicker(red: 0, green: 170, blue: 116)
    static let thirdColor = colorPicker(red: 20, green: 0, blue: 204)
    static let gradientColors = [firstColor.cgColor, secondColor.cgColor, thirdColor.cgColor]
    static func colorPicker(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor {
        let color = UIColor(red: red / 255, green: green / 255, blue: blue / 255, alpha: 1.0)
        return color
    }
}

请给我一些有关如何将其实现为扩展的建议。

1 个答案:

答案 0 :(得分:0)

我可以在您的代码中看到的主要一件事是,您尝试在viewDidLoad中进行绘制。请勿这样做,除其他问题外,此时的帧大小尚未正确设置。如果要UIView进行绘制,请从UIView派生一个类,并使用该类的draw方法进行绘制。

如果您希望创建的radialGradientLayer CALayer进行绘制(当前为空),请从CALayer派生一个子类,并实现其{{1} }方法。