2013-05-08 831 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];