将图层阴影剪切为宽度而不是高度?

时间:2012-05-22 05:14:17

标签: iphone objective-c ios core-graphics

我正在为我的视图层添加阴影,如下所示:

    self.view.layer.shadowOffset = CGSizeZero;
    self.view.layer.shadowOpacity = 0.10f;
    self.view.layer.shadowRadius = 5.0f;
    self.view.layer.shadowColor = [UIColor blackColor].CGColor;
    self.view.layer.shadowPath = [UIBezierPath bezierPathWithRect:
                                 CGRectMake(self.view.bounds.origin.x, self.view.bounds.origin.y, self.view.bounds.size.width - 5.0, self.view.bounds.size.height)].CGPath;
    self.view.clipsToBounds = NO;

我想要做的是以某种方式剪切阴影,使其不会超出宽度,但会超出高度。基本上,我只想要一个90度的阴影,而不是我的边界周围的阴影。我尝试从bezierRect宽度中减去shadowRadius量,但这会稍微扰乱底部的阴影流。

有关如何实现这一目标的任何想法?

1 个答案:

答案 0 :(得分:1)

您可以添加新的“容器”视图,并将视图(内容视图)添加为子视图。容器视图应高于视图但宽度相同。如果您将容器视图设置为剪切到其边界,它将剪切侧面的阴影,但允许底部和顶部的阴影。

 _________  
| _______ |  <-- container
||       ||
||       ||  <-- your view (inside container)
||_______||
|`````````|  <-- shadow of your view (inside container)
|_________|

在代码中,这看起来像

// contentView is already created and configured...
UIView *containerView = [[UIView alloc] initWithFrame:
                                 CGRectInset([contentView frame], 
                                             0,         // keep the same width 
                                             -radius)]; // increase the height
[[self view] addSubview:containerView];
[contentView setCenter:CGPointMake(CGRectGetMidX([contentView bounds]), 
                                   CGRectGetMidY([contentView bounds]));
[containerView addSubview:contentView];
[containerView setClipsToBounds:YES];