CAGradientLayer not working [duplicate]

夙愿已清 提交于 2019-12-06 21:38:32

问题


I created a new project. I linked QuartzCore.framework and imported <QuartzCore/QuartzCore.h> in the ViewController.m.

And here is the code.

- (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
}

I tried setting the view's background color to clearColor, calling it in the viewDidAppear, but none of them worked. I really don't know what I'm missing. Thanks in any help.


回答1:


Your color array should be NSArray *colorArray = @[(id)colorOne.CGColor, (id)colorTwo.CGColor];, because the colors array takes CGColorRefs, rather than UIColors, annoyingly enough - see the CGGradientLayer docs



来源:https://stackoverflow.com/questions/33060648/cagradientlayer-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!