放暗影的矩形(drawRect中:(的CGRect)RECT)

问题描述:

我做了一个矩形与此代码和它的工作原理:放暗影的矩形(drawRect中:(的CGRect)RECT)

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

但现在我想提出一个影子,我想这一点:

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

但Xcode中告诉我NSMakeSize : Sending 'int' to parameter of incompatible type 'CGSize'

大约是阴影的正确形式? 谢谢!

+0

尝试'CGSizeMake'而不是'NSMakeSize'? – Larme

+0

我改变了你的评论我现在xcode不告诉我的错误,但没有出现阴影 – user2958588

+0

如何使用CGContextSetShadow()'? – Larme

您应该在绘制应具有阴影的对象的函数之前调用CGContextSetShadow(...)函数。下面是完整的代码:

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

备注:

我注意到您提供一些随机值CGContextAddRect(context, CGRectMake(60, 60, 100, 1));。您只应在通过rect参数收到的矩形内绘制。

+0

ooooo呀!现在我可以看到阴影了,非常感谢..好吧,你在你的评论中有理由,所以它取决于矩形? – user2958588

+0

@ user2958588,根据苹果文档:'你应该限制任何绘图到在rect参数中指定的矩形。' 原因是我认为这是为了提高渲染性能。 请注意,矩形大小和原点可能与您的视图框架不同,因为视图的某些部分可能已经呈现,因此iOS可能只请求一部分重新渲染。 – Keenle