1

如何用 3 种颜色绘制 CGGradient?

我有一个像这样的数组:

CFArrayRef colors = (__bridge CFArrayRef) [NSArray arrayWithObjects:(id)lightGradientColor.CGColor,
                                           (id)darkGradientColor.CGColor, (id)lightGradientColor.CGColor,
                                           nil];

但我没有看到中间的深色,顶部和底部有光,而只是顶部有光,直到底部都是黑暗的。

4

2 回答 2

3

您是否尝试过指定/验证颜色的位置?范围是 [0...1]:

const CGFloat locations[3] = {0.0, 0.5, 1.0};
CGGradientRef grad = CGGradientCreateWithColors(colorspace, colors, locations);

注意:上面的位置应该与传递参数0的位置相同。locations

于 2012-07-30T08:18:30.630 回答
0

使用 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 放在颜色上会更明显:

CGGradient CAGradientLayer

于 2016-11-28T14:04:35.600 回答