ios – CAGradientLayer不工作

参见英文答案 > Drawing gradient on UIView not working with iOS 91个
我创建了一个新项目.我链接了QuartzCore.framework并导入了< QuartzCore / QuartzCore.h>在ViewController.m中.

这是代码.

- (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中调用它,但它们都没有工作.我真的不知道自己错过了什么.在任何帮助下谢谢.

解决方法

你的颜色数组应该是NSArray * colorArray = @ [(id)colorOne.CGColor,(id)colorTwo.CGColor] ;,因为colors数组需要CGColorRefs,而不是UIColors,令人讨厌 – 请参阅 the CGGradientLayer docs

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...