Search code examples
objective-cdrawrectcgrectmake

Put shadow to a rectangle (drawRect:(CGRect)rect)


I did a rectangle with this code and it works:

- (void)drawRect:(CGRect)rect{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextAddRect(context, CGRectMake(60, 60, 100, 1));
    CGContextStrokePath(context);
}

But now i want to put a shadow, I tried with this:

NSShadow* theShadow = [[NSShadow alloc] init];
[theShadow setShadowOffset:NSMakeSize(10.0, -10.0)];
[theShadow setShadowBlurRadius:4.0];

But xcode tell me about NSMakeSize : Sending 'int' to parameter of incompatible type 'CGSize'

Which is the correct form about shadows? Thanks!!


Solution

  • You should invoke CGContextSetShadow(...) function before the functions that draw object that should have a shadow. Here is the complete code:

    - (void)drawRect:(CGRect)rect {
        // define constants
        const CGFloat shadowBlur = 5.0f;
        const CGSize shadowOffset = CGSizeMake(10.0f, 10.0f);
    
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);
    
        // Setup shadow parameters. Everithyng you draw after this line will be with shadow
        // To turn shadow off invoke CGContextSetShadowWithColor(...) with NULL for CGColorRef parameter.
        CGContextSetShadow(context, shadowOffset, shadowBlur);
    
        CGRect rectForShadow = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width - shadowOffset.width - shadowBlur, rect.size.height - shadowOffset.height - shadowBlur);
        CGContextAddRect(context, rectForShadow);
        CGContextStrokePath(context);
    }
    

    Remarks:

    I have noticed that you provide some random values to CGContextAddRect(context, CGRectMake(60, 60, 100, 1));. You should draw only within the rectangle that you receive through rect parameter.