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

半城伤御伤魂 提交于 2020-01-06 08:22:06

问题


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!!


回答1:


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.



来源:https://stackoverflow.com/questions/24636304/put-shadow-to-a-rectangle-drawrectcgrectrect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!