简体   繁体   中英

shadow does not show in drawRect:(CGrect)rect,objective

My goal is 1. add gradient for my view (done) 2. add drop shadow for the bottom edge of my view ( issue at here ) What I am doing is :

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

}

However, what I am getting is the picture below without shadow at all

Am I on the right track but missing something in the middle ? Please help if you have any ideas.. 在此处输入图片说明

You need to set the shadow properties before drawing whatever it is that's supposed to have the shadow. Put your call to CGContextSetShadowWithColor before the call to CGContextStrokeRect .

Also, the offset should probably not be as large as you're making it. The shadow offset controls how much the shadow is offset from the pixels that were drawn with that shadow, so unless you want the shadow to actually start very far away from your rect you probably want an offset of just a pixel or so, like CGSizeMake(0.0, 1.0) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM