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



码:

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

最佳答案

这是通用梯度生成器:

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

关于objective-c - UIView中的圆柱外观Gradient,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12184317/

10-13 04:28