如何同时向 UIView 添加顶角、顶边框和顶阴影
Posted
技术标签:
【中文标题】如何同时向 UIView 添加顶角、顶边框和顶阴影【英文标题】:How to add top corners, top border and top shadow to a UIView at the same time 【发布时间】:2016-05-16 08:18:02 【问题描述】:我需要在 UIView 上添加几种效果,使其左上角和右上角圆角,圆角曲线上有白色边框和暗阴影,如下图所示:
我创建了一个继承自 UIView 的 MSHTablePaneCell 类,然后重写了它的 drawRect
方法:
static const CGFloat kCornerRadius = 15;
@implementation MSHTablePaneCell ()
- (void)drawRect:(CGRect)rect
[super drawRect:rect];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:(UIRectCornerTopLeft |UIRectCornerTopRight) cornerRadii:CGSizeMake(kCornerRadius, kCornerRadius)];
// 1. mask round corner
CAShapeLayer *roundLayer = [CAShapeLayer layer];
roundLayer.path = path.CGPath;
roundLayer.frame = self.bounds;
// roundLayer.cornerRadius = 10.0;
self.layer.mask = roundLayer;
// 2. add border to round corner curve
UIBezierPath *topCurvepath = [UIBezierPath bezierPath];
[topCurvepath moveToPoint:CGPointMake(0, kCornerRadius)];
[topCurvepath addQuadCurveToPoint:CGPointMake(kCornerRadius, 0) controlPoint:CGPointMake(0, 0)];
[topCurvepath addLineToPoint:CGPointMake(CGRectGetWidth(self.frame)-kCornerRadius, 0)];
[topCurvepath addQuadCurveToPoint:CGPointMake(CGRectGetWidth(self.frame), kCornerRadius) controlPoint:CGPointMake(CGRectGetWidth(self.frame), 0)];
CAShapeLayer *topBorderLayer = [CAShapeLayer layer];
topBorderLayer.lineWidth = 4.0;
topBorderLayer.borderColor = [UIColor redColor].CGColor;
topBorderLayer.path = topCurvepath.CGPath;
[self.contentView.layer addSublayer:topBorderLayer];
@end
但是,通过上面的代码,我得到了如下的最终图片:
无论我设置哪个属性,topCurvePath
都以黑色背景显示,我该如何解决这个问题?先谢谢了~
【问题讨论】:
您是否尝试设置图层的borderWidth、strokeColor、backgroudColor 属性? @AlexKosyakov 是的...~~~~(>_ topBorderLayer.fillColor = [UIColor yourColor].CGColor ? 是的! fillColor 作品。。。谢谢 我已将其发布为答案。 【参考方案1】:topBorderLayer.fillColor = [UIColor yourColor].CGColor
【讨论】:
以上是关于如何同时向 UIView 添加顶角、顶边框和顶阴影的主要内容,如果未能解决你的问题,请参考以下文章