2013-04-04 40 views
2

我的目标是 1.为我的视图添加渐变(完成) 2.为我的视图底边添加阴影(问题在这里) 什么我做的是:阴影不显示在drawRect中:(CGrect)矩形,物镜

- (void)drawRect:(CGRect)rect { 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    UIColor *whiteColor   = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0]; 
    UIColor *lightGrayColor  = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0 blue:230.0/255.0 alpha:1.0]; 

    CGRect paperRect   = self.bounds; 

    // Fill with gradient 
    [self drawLinearGradient:context for:paperRect start:whiteColor.CGColor end:lightGrayColor.CGColor]; 

    CGContextSetStrokeColorWithColor(context, [UIColor lightGrayColor].CGColor); 
    CGContextSetLineWidth(context, .9); 
    CGContextStrokeRect(context, paperRect); 

    // Add shadow 
    CGContextSetShadowWithColor(context, CGSizeMake(0, self.frame.size.height), 9.0, [UIColor blueColor].CGColor); 

} 
-(void)drawLinearGradient:(CGContextRef)context for:(CGRect)rect start:(CGColorRef)startColor end:(CGColorRef)endColor { 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
    CGFloat locations[]   = { 0.0, 1.0 }; 

    NSArray *colors    = [NSArray arrayWithObjects:(__bridge id)startColor, (__bridge id)endColor, nil]; 

    CGGradientRef gradient  = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations); 

    CGPoint startPoint   = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect)); 
    CGPoint endPoint   = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect)); 

    CGContextSaveGState(context); 
    CGContextAddRect(context, rect); 
    CGContextClip(context); 
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0); 
    CGContextRestoreGState(context); 

    CGGradientRelease(gradient); 
    CGColorSpaceRelease(colorSpace); 

} 

然而,我所得到的是下面的图片中没有影子都没有

我在正确的轨道上,但在中间失去了一些东西?请帮助,如果您有任何意见.. enter image description here

回答

1

您需要设置阴影属性图纸不管它是什么的应该有阴影。在致电CGContextStrokeRect之前,请拨打CGContextSetShadowWithColor

此外,偏移量可能不会像您所做的那样大。阴影偏移量控制阴影与用该阴影绘制的像素之间的偏移量,因此除非您希望阴影实际上距离矩形很远,否则您可能只需要一个像素左右的偏移量,如CGSizeMake(0.0, 1.0)