0

我想绘制具有圆柱形外观和阴影效果的条(如下图所示)。有人可以帮助为以下外观定义线性渐变。

圆柱条形图

代码:

-(void)drawRect:(CGRect)rect {
    //UIview Back color is red or green
    CGGradientRef   glossGradient;
    CGColorSpaceRef rgbColorspace;
    CGContextRef    currentContext  = UIGraphicsGetCurrentContext();
    size_t          num_locations   = 4;
    CGFloat locations[4]            = { 0.0,0.7,0.9,1.0 };

    CGFloat components[16]          = { 0.0, 0.0, 0.0, 0.01,
                                        0.0, 0.0, 0.0, 0.1,
                                        0.0, 0.0, 0.0, 0.2,
                                        0.0, 0.0, 0.0, 0.5 
                                      };


    rgbColorspace        = CGColorSpaceCreateDeviceRGB();
    glossGradient        = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);

    CGRect currentBounds = self.bounds;
    CGPoint topCenter    = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
    CGPoint midCenter    = CGPointMake(CGRectGetMidX(currentBounds), currentBounds.size.height);

    CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0);
    CGGradientRelease(glossGradient);
    CGColorSpaceRelease(rgbColorspace); 
}
4

1 回答 1

1

这是一个通用的渐变生成器:

    CGGradientRef makeGradient2(NSArray *colors, CGFloat *stops)
    {
        size_t nc = 4;
        NSInteger colorSize = nc * sizeof(CGFloat);
        CGFloat *theComponents = malloc( [colors count] * colorSize );
        CGFloat *compPtr = theComponents;

        for (int i=0; i < colors.count; i++){
            UIColor *color = [colors objectAtIndex:i];
            CGColorRef cgColor = [color CGColor];
            const CGFloat *components = CGColorGetComponents(cgColor);

            memmove(compPtr, components, colorSize);
            compPtr += nc;
        }
        CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
        CGGradientRef gradient = CGGradientCreateWithColorComponents (cs, theComponents, stops, colors.count);
        CGColorSpaceRelease(cs);
        free(theComponents);

        return gradient;
    }

称之为(这会创建一个中间最亮的三部分灰色渐变)

    CGFloat stops[] = { 0.0, 0.5, 1.0};
    gradient = makeGradient2([NSArray arrayWithObjects:
                               [UIColor colorWithRed:.2 green:.2 blue:.2 alpha:1.0],
                               [UIColor colorWithRed:.5 green:.5 blue:.5 alpha:1.0],
                               [UIColor colorWithRed:.2 green:.2 blue:.2 alpha:1.0],
                               nil], stops);

然后你可以用它来绘制(对于从左到右的渐变):

    CGContextDrawLinearGradient(gc, gradient, CGPointMake(0.0, 0.0), CGPointMake(rect.size.width, 0.0), 0);
于 2012-08-29T19:19:00.363 回答