這是我的完全紋理/ AsyncDisplayKi基於t的實現。這允許一個完全通用的漸變節點類,它不修復整個類的任何值,其他解決方案到目前爲止都是強制的,因爲drawRect是一個類函數,而不是一個實例函數。
class GradientNode: ASDisplayNode {
private let startUnitPoint: CGPoint
private let endUnitPoint: CGPoint
private let colors: [UIColor]
private let locations: [CGFloat]?
override class func draw(_ bounds: CGRect, withParameters parameters: Any?, isCancelled isCancelledBlock:() -> Bool, isRasterizing: Bool) {
guard let parameters = parameters as? GradientNode else {
CCLog.assert("Expected type SimpleGradientNode to be returned")
return
}
// Calculate the start and end points
let startUnitX = parameters.startUnitPoint.x
let startUnitY = parameters.startUnitPoint.y
let endUnitX = parameters.endUnitPoint.x
let endUnitY = parameters.endUnitPoint.y
let startPoint = CGPoint(x: bounds.width * startUnitX + bounds.minX, y: bounds.height * startUnitY + bounds.minY)
let endPoint = CGPoint(x: bounds.width * endUnitX + bounds.minX, y: bounds.height * endUnitY + bounds.minY)
let context = UIGraphicsGetCurrentContext()!
context.saveGState()
context.clip(to: bounds)
guard let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(),
colors: parameters.colors.map { $0.cgColor } as CFArray,
locations: parameters.locations) else {
CCLog.assert("Unable to create CGGradient")
return
}
context.drawLinearGradient(gradient,
start: startPoint,
end: endPoint,
options: CGGradientDrawingOptions.drawsAfterEndLocation)
context.restoreGState()
}
init(startingAt startUnitPoint: CGPoint, endingAt endUnitPoint: CGPoint, with colors: [UIColor], for locations: [CGFloat]? = nil) {
self.startUnitPoint = startUnitPoint
self.endUnitPoint = endUnitPoint
self.colors = colors
self.locations = locations
super.init()
}
override func drawParameters(forAsyncLayer layer: _ASDisplayLayer) -> NSObjectProtocol? {
return self
}
所有人需要做的就是創建一個GradientNote並填寫init()函數中的參數。然後將它視爲一個常規節點,讓ASDK完成剩下的工作!
coverTitleBackgroundNode = GradientNode(startingAt: CGPoint(x: 0.5, y: 1.0),
endingAt: CGPoint(x: 0.5, y: 0.0),
with: [UIColor.black.withAlphaComponent(Constants.CoverTitleBackgroundBlackAlpha), UIColor.clear])
coverTitleBackgroundNode!.isLayerBacked = true
coverTitleBackgroundNode!.isOpaque = false
automaticallyManagesSubnodes = true
一般編輯節點的觀點應該是在主線程,如果沒有它拋出一個異常 - 「這個方法必須被稱爲主線程」。我試圖找到一個很酷的例子,說明如何以相對簡單的方式實現它。 –