This is largely based on the decision of Sartak Sharmas. I made a UIView extension, and I decided that readability and type conversions could be slightly improved:
extension UIView { func setGradient(colors: [CGColor], angle: Float = 0) { let gradientLayerView: UIView = UIView(frame: CGRect(x:0, y: 0, width: bounds.width, height: bounds.height)) let gradient: CAGradientLayer = CAGradientLayer() gradient.frame = gradientLayerView.bounds gradient.colors = colors let alpha: Float = angle / 360 let startPointX = powf( sinf(2 * Float.pi * ((alpha + 0.75) / 2)), 2 ) let startPointY = powf( sinf(2 * Float.pi * ((alpha + 0) / 2)), 2 ) let endPointX = powf( sinf(2 * Float.pi * ((alpha + 0.25) / 2)), 2 ) let endPointY = powf( sinf(2 * Float.pi * ((alpha + 0.5) / 2)), 2 ) gradient.endPoint = CGPoint(x: CGFloat(endPointX),y: CGFloat(endPointY)) gradient.startPoint = CGPoint(x: CGFloat(startPointX), y: CGFloat(startPointY)) gradientLayerView.layer.insertSublayer(gradient, at: 0) layer.insertSublayer(gradientLayerView.layer, at: 0) } }
Add this to your new or linked Swift file, and all you have to do is call either myView.setGradient(colors: gradientColorsArray) or myView.setGradient(colors: gradientColorsArray, angle: 90) .
easytarget
source share