如何将渐变添加到ASDisplayNode或ASButtonNode

时间:2017-04-10 10:56:33

标签: ios gradient cagradientlayer asyncdisplaykit

我希望为ASDisplayNode / ASButtonNode添加渐变背景。 我尝试过创建一个渐变图层并将其添加为像这样的子图层 -

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = button.frame;
gradient.colors = @[[UIColor redColor], [UIColor blueColor]];
[button.view.layer insertSublayer:gradient atIndex:0];

其中button的类型为ASButtonNode,但这只是为按钮提供了白色背景。我无法找到很多文档来实现这一目标。

如何在给定UIColorCGFloat角度的数组的情况下添加背景?

由于

3 个答案:

答案 0 :(得分:1)

这是我完全基于Texture / AsyncDisplayKit的实现。这允许完全通用的Gradient Node类不修复整个类的任何值,其他解决方案到目前为止强制执行,因为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

答案 1 :(得分:0)

你在AsyncDisplayKit的GitHub问题上问了同样的问题: https://github.com/facebookarchive/AsyncDisplayKit/issues/3253

您已经回答了两种可能性:

  

1:创建CAGradientLayer并将其添加为节点的子层

     

2:覆盖节点的+(void)draw ...方法并在那里绘制渐变。

第一个选项必须在主线程中,这样才不会授予我们强大的ASDK权力。 第二个选项更复杂,但我可以从ASDK示例项目中发布一些示例。

基于 https://github.com/facebookarchive/AsyncDisplayKit/blob/master/examples/VerticalWithinHorizontalScrolling/Sample/RandomCoreGraphicsNode.m

https://www.raywenderlich.com/124311/asyncdisplaykit-2-0-tutorial-getting-started

<强> 1。子类ASDisplayNode

#import <AsyncDisplayKit/AsyncDisplayKit.h>

@interface GradientNode : ASDisplayNode

@end

<强> 2。覆盖drawRect方法(基本渐变有2种颜色 - 黑色到透明)

@implementation GradientNode

+(void)drawRect:(CGRect)bounds withParameters:(id)parameters isCancelled:
    (asdisplaynode_iscancelled_block_t)isCancelledBlock isRasterizing:
    (BOOL)isRasterizing{

        CGFloat locations[2];
        NSMutableArray *colors = [NSMutableArray arrayWithCapacity:2];
        [colors addObject:(id)[[UIColor clearColor] CGColor]];
        locations[0] = 0.0;
        [colors addObject:(id)[[UIColor blackColor] CGColor]];
        locations[1] = 1.0;

        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, 
        (CFArrayRef)colors, locations);

        CGContextDrawLinearGradient(ctx, gradient, CGPointZero, 
        CGPointMake(bounds.size.width, bounds.size.height), 0);

        CGGradientRelease(gradient);
        CGColorSpaceRelease(colorSpace);
    }

    @end

第3。设置节点(重要!当使用具有清晰颜色的渐变时,否则会绘制一个不透明的黑色视图)

_gradientNode = [GradientNode new];
_gradientNode.layerBacked = YES;
_gradientNode.opaque = NO;

答案 2 :(得分:0)

extension ASDisplayNode {
    func gradient(from color1: UIColor, to color2: UIColor) {
        DispatchQueue.main.async {

            let size = self.view.frame.size
            let width = size.width
            let height = size.height


            let gradient: CAGradientLayer = CAGradientLayer()
            gradient.colors = [color1.cgColor, color2.cgColor]
            gradient.locations = [0.0 , 1.0]
            gradient.startPoint = CGPoint(x: 0.0, y: height/2)
            gradient.endPoint = CGPoint(x: 1.0, y: height/2)
            gradient.cornerRadius = 30
            gradient.frame = CGRect(x: 0.0, y: 0.0, width: width, height: height)
            self.view.layer.insertSublayer(gradient, at: 0)
        }
    }
}

示例:

node.gradient(from: .white, to: .red)