2014-07-08 40 views
0

我做了一個矩形與此代碼和它的工作原理:放暗影的矩形(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

回答

1

您應該在繪製應具有陰影的對象的函數之前調用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

相關問題