Search code examples
iosobjective-ccore-graphicsdrawrectrounded-corners

How to add top corners, top border and top shadow to a UIView at the same time


I need to add several kinds of effects on a UIView with rounding its top left and top right corners, white border and dark shadow on its rounded corner curve like the picture below: enter image description here

I created a MSHTablePaneCell class inherited from UIView and then overrided its drawRect method:

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

However, with code above, I just got the final picture like below: enter image description here

No matter which property I set, the topCurvePath just displayed with black background color, how I can fix this problem? Thanks in advance~


Solution

  • topBorderLayer.fillColor = [UIColor yourColor].CGColor