CAGradientLayer 不工作

CAGradientLayer not working

我创建了一个新项目。我在 ViewController.m.

中链接了 QuartzCore.framework 并导入了 <QuartzCore/QuartzCore.h>

这是代码。

- (void)viewDidLoad {
    [super viewDidLoad];

    NSLog(@"view height %f", self.view.frame.size.height); // returns 667 on iPhone 6
    NSLog(@"view width %f", self.view.frame.size.width); // returns 375 on iPhone 6

    NSLog(@"layers count %lu", self.view.layer.sublayers.count); // returns 2

    // Gradient
    UIColor *colorOne = [UIColor blueColor];
    UIColor *colorTwo = [UIColor greenColor];
    NSArray *colorArray = @[colorOne, colorTwo];

    NSNumber *locationOne = [NSNumber numberWithFloat:0.0];
    NSNumber *locationTwo = [NSNumber numberWithFloat:1.0];
    NSArray *locationArray = @[locationOne, locationTwo];

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = self.view.frame;
    gradientLayer.colors = colorArray;
    gradientLayer.locations = locationArray;

    [self.view.layer insertSublayer:gradientLayer atIndex:0];
    //[self.view.layer insertSublayer:gradientLayer above:[self.view.layer.sublayers firstObject]]; // didn't work either

    NSLog(@"layers count %lu", self.view.layer.sublayers.count); //returns 3
}

我尝试将视图的背景颜色设置为 clearColor,在 viewDidAppear 中调用它,但其中 none 行得通。我真的不知道我错过了什么。感谢您的帮助。

你的颜色数组应该是 NSArray *colorArray = @[(id)colorOne.CGColor, (id)colorTwo.CGColor];,因为 colors 数组需要 CGColorRef 秒,而不是 UIColor 秒,这很烦人 - 请参阅 the CGGradientLayer docs