Skip to content

Instantly share code, notes, and snippets.

@GeekTree0101
Created September 16, 2018 04:06
Show Gist options
  • Save GeekTree0101/50049a18ea1d5647cc1458231396a10c to your computer and use it in GitHub Desktop.
Save GeekTree0101/50049a18ea1d5647cc1458231396a10c to your computer and use it in GitHub Desktop.
CAGradientLayer with Texture Example
import AsyncDisplayKit
extension ASDisplayNode {
enum GradientDirection {
case horizontal
case vertical
case adjust(CGPoint, CGPoint)
var points: (start: CGPoint, end: CGPoint) {
switch self {
case .horizontal:
return (start: .init(x: 0.0, y: 0.5), end: .init(x: 1.0, y: 0.5))
case .vertical:
return (start: .init(x: 0.5, y: 0.0), end: .init(x: 0.5, y: 1.0))
case .adjust(let start, let end):
return (start: start, end: end)
}
}
}
func gradientBackgroundColor(_ colors: [CGColor], direction: GradientDirection) {
guard !self.hasGradientLayer else { return }
DispatchQueue.main.async {
self.backgroundColor = .clear
self.clipsToBounds = true
let gradient = CAGradientLayer()
gradient.frame = .init(origin: .zero, size: self.calculatedSize)
gradient.colors = colors
gradient.startPoint = direction.points.start
gradient.endPoint = direction.points.end
self.layer.insertSublayer(gradient, at: 0)
}
}
var hasGradientLayer: Bool {
return self.layer
.sublayers?
.filter({ $0 is CAGradientLayer }).isNotEmpty ?? false
}
}
// Example
class TestNode: ASDisplayNode {
struct Const {
static let coverGradientStartColor: CGColor =
UIColor(white: 0.0, alpha: 0.28).cgColor
static let coverGradientEndColor: CGColor =
UIColor(white: 0.0, alpha: 0.0).cgColor
}
let coverImageNode: ASNetworkImageNode = {
let node = ASNetworkImageNode()
node.contentMode = .scaleAspectFill
node.backgroundColor = Const.coverDefaultColor
return node
}()
override func layoutDidFinish() {
super.layoutDidFinish()
self.coverGradientNode
.gradientBackgroundColor([Const.coverGradientStartColor,
Const.coverGradientEndColor],
direction: .vertical)
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
// ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment