2013-04-04 56 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)