我的目标是为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
}
}
请给我一个关于如何实现它作为扩展的建议。
我在你的代码中可以看到的一个主要问题是你尝试在viewDidLoad
中进行绘图。不要这样做,除了其他问题之外,当时框架尺寸还没有正确设置。如果你想让UIView
做绘图,那么从UIView
派生一个类,并在该类的draw
方法中进行绘制。
如果你想要你创建的radialGradientLayer
CALayer
来做绘图(它当前只是空的),那么从CALayer
派生一个子类,并实现它的drawInContext
方法。