CALayer:如何调用绘制函数?
CALayer: How do I call the draw function?
我将 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()
.
什么时候画画不由你说了算。系统处理那个。但需要绘图时,由您告诉系统。
我将 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()
.
什么时候画画不由你说了算。系统处理那个。但需要绘图时,由您告诉系统。