2013-05-08 47 views
3

我想爲路徑添加發光效果,例如焦點附近的藍色發光(OS X)界面元素。向CAShapeLayer添加陰影,以便內部保持透明

我用了一個CAShapeLayer用(矩形)路徑:

self.borderLayer = [CAShapeLayer layer]; 
CGPathRef path = CGPathCreateWithRect(self.bounds, NULL); 
[self.borderLayer setPath:path]; 
CGPathRelease(path); 

這到底給了我與它周圍的邊框的透明的UIView。 (在我的具體情況下,這是一條帶有額外動畫的虛線,但對於這個特定問題無關緊要)

我玩過CALayer的陰影屬性,但它們會一直填充整個圖層。

self.borderLayer.shadowPath = self.borderLayer.path; 
self.borderLayer.shouldRasterize = YES; 

我想要的是,只有周圍的行UIViews下降了陰影,使的UIView內保持透明。

回答

3

我有類似的問題看到陰影裏面我想要它而不是輝光。我通過使用兩個CALayers解決了這個問題。其中一個,在代碼中,'_bg'用於背景(在我的案例中,黑色,不透明度爲0.55)和白色邊框。代碼'_shadow'中的其他圖層具有清晰的背景,並添加了發光效果。 _bg是_shadow圖層的子視圖。下面是相關的代碼:

_bg = [CALayer layer]; 
_shadow = [CALayer layer]; 

[self.layer insertSublayer:_shadow atIndex:0]; 
[_shadow addSublayer:_bg]; 

_bg.frame = self.bounds; 
_bg.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:.55].CGColor; 
_bg.cornerRadius=20.0; 
_bg.borderColor=[UIColor whiteColor].CGColor; 
_bg.borderWidth=2.0; 

_shadow.frame=self.bounds; 
_shadow.masksToBounds=NO; 
_shadow.backgroundColor = [UIColor clearColor].CGColor; 
_shadow.cornerRadius=3.0; 
_shadow.shadowRadius=3.0; 
_shadow.shadowColor=[UIColor whiteColor].CGColor; 
_shadow.shadowOpacity=0.6; 
_shadow.shadowOffset=CGSizeMake(0.0, 0.0); 
2

你可以嘗試這樣的事情:

//background layer of the shadow layer 
    contentViewBackgroundLayer = [CALayer layer]; 
    contentViewBackgroundLayer.frame = contentView.bounds; 
    contentViewBackgroundLayer.backgroundColor = someColor.CGColor; 
    //shadow layer 
    contentViewShadowLayer = [CALayer layer]; 
    [contentViewShadowLayer addSublayer:contentViewBackgroundLayer]; 
    contentViewShadowLayer.backgroundColor = [UIColor clearColor].CGColor; 
    //shadowRadius 
    contentViewShadowLayer.shadowRadius = 10.0; 
    contentViewShadowLayer.shadowColor = [UIColor blackColor].CGColor; 
    contentViewShadowLayer.shadowOpacity = 0.5; 
    contentViewShadowLayer.shadowOffset = CGSizeMake(0.0, 0.0); 
    //Important!!!! add mask to shadowLayer 
    contentViewBackgroundLayer.frame = contentView.bounds; 
    contentViewShadowLayer.frame = contentView.bounds; 
    CGRect rect = CGRectMake(contentViewShadowLayer.bounds.origin.x - 20, contentViewShadowLayer.bounds.origin.y - 20, contentViewShadowLayer.bounds.size.width + 40, contentViewShadowLayer.bounds.size.height + 40); 
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:rect]; 
    [path appendPath:[UIBezierPath bezierPathWithRect:CGRectMake(0, 0, contentView.bounds.size.width, contentView.bounds.size.height)]]; 
    //a rectangle which is transparent surrounded by a bigger rectangle 
    CAShapeLayer *shapeLayer = [CAShapeLayer layer]; 
    shapeLayer.fillRule = kCAFillRuleEvenOdd; 
    shapeLayer.path = [path CGPath]; 
    contentViewShadowLayer.mask = shapeLayer; 
    [contentView.layer insertSublayer:contentViewShadowLayer atIndex:0];