使用 CGGradient 而不是 CAGardientLayer 传递多种颜色以获得更平滑的结果:
A. 创建一个自定义 UIView 类,在标题中使用 @property NSArray * 颜色。在实现文件中,粘贴以下 drawRect 方法。
-(void)drawRect:(CGRect)rect {
    //1. create vars
    float increment = 1.0f / (colours.count-1);
    CGFloat * locations = (CGFloat *)malloc((int)colours.count*sizeof(CGFloat));
    CFMutableArrayRef mref = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
    //2. go through the colours, creating cgColors and locations
    for (int n = 0; n < colours.count; n++){
        CFArrayAppendValue(mref, (id)[colours[n] CGColor]);
        locations[n]=(n*increment);
    }
    //3. create gradient
    CGContextRef ref = UIGraphicsGetCurrentContext();
    CGColorSpaceRef spaceRef = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradientRef = CGGradientCreateWithColors(spaceRef, mref, locations);
    CGContextDrawLinearGradient(ref, gradientRef, CGPointMake(0.0, 0.0), CGPointMake(0.0, self.frame.size.height), kCGGradientDrawsAfterEndLocation);
    CGColorSpaceRelease(spaceRef);
    CGGradientRelease(gradientRef);
}
B. 在你想使用自定义类的 viewController 中,初始化它,设置框架和它的颜色。它适用于不止一种颜色,在这种情况下从上到下运行。
Background * bg = [Background new];
[bg setFrame:self.view.bounds];
[bg setColours:@[[UIColor blueColor],[UIColor purpleColor]]];
[self.view addSubview:bg];
这是一个比使用 CAGradientLayer 更平滑的渐变,如果将 alpha 放在颜色上会更明显:
 
