2012-08-29 125 views
0

我想用圆柱形外观和阴影效果绘制条形(如下图所示)。有人可以帮助定义线性渐变以获得下面的外观和感觉。圆柱形外观UIView中的渐变

cylindrical Bar Graph

代码:

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

回答

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);