我将 CALayer 子类化以创建径向渐变(我从 this code here 开始)。问题是我需要更改绘图函数中的渐变颜色。我希望每次更改 colors
时都能够重新绘制图层。我不能直接调用 draw(in:)
因为我不知道要使用什么 CGContext
。有什么想法吗?
import Foundation
import UIKit
class CARadialGradientLayer: CALayer {
required override init() {
super.init()
needsDisplayOnBoundsChange = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required override init(layer: Any) {
super.init(layer: layer)
}
public var colors = [UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5).cgColor, UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.00).cgColor] {
didSet {
/* Redraw the layer to update colors */
}
}
override func draw(in ctx: CGContext) {
ctx.saveGState()
let colorSpace = CGColorSpaceCreateDeviceRGB()
var locations = [CGFloat]()
for i in 0...colors.endIndex {
locations.append(CGFloat(i) / CGFloat(colors.count))
}
let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: locations)
let center = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)
let radius = min(bounds.width / 2.0, bounds.height / 2.0)
ctx.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: radius, options: CGGradientDrawingOptions(rawValue: 0))
}
}
最佳答案
在didSet
中,调用setNeedsDisplay()
。
绘制发生时不由您决定。系统处理那个。但是您可以在需要绘图时告诉系统。
关于swift - CALayer:如何调用绘制函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48327326/