使用UIBezierPath和阴影创建视图?

5
我有一个位于UITableViewCell中的视图,它有3个圆角和阴影。我正在使用UIBezierPath来实现圆角,但无法设置阴影。
以下是所用的代码行:
   CGRect bounds2 = cell.backgroundMessageView.bounds;
   UIBezierPath *maskPath2 = [UIBezierPath bezierPathWithRoundedRect:bounds2
                                                               byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight|UIRectCornerBottomRight
                                                                     cornerRadii:CGSizeMake(5, 5)];

   CAShapeLayer *maskLayer2 = [CAShapeLayer layer];
   maskLayer2.frame = bounds2;
   maskLayer2.path = maskPath2.CGPath;


   cell.backgroundMessageView.layer.mask = maskLayer2;

    //drop shadow   

   [cell.backgroundMessageView.layer setShadowColor:[UIColor blackColor].CGColor];
   [cell.backgroundMessageView.layer setShadowOpacity:1];
   [cell.backgroundMessageView.layer setShadowRadius:3.0];
   [cell.backgroundMessageView.layer setShadowOffset:CGSizeMake(2, 2)];

这是英语文本,翻译成中文如下:

这应该是结果:

enter image description here

有什么想法吗?

谢谢!


1
请将您的解决方案作为答案给出。 - user3182143
1个回答

10

解决方案!

    cell.backgroundMessageView.layer.cornerRadius=5;
    CGRect bounds2 = cell.backgroundMessageView.bounds;
    UIBezierPath *maskPath2 = [UIBezierPath bezierPathWithRoundedRect:bounds2
                                                                    byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight|UIRectCornerBottomRight
                                                                          cornerRadii:CGSizeMake(5, 5)];

    CAShapeLayer *maskLayer2 = [CAShapeLayer layer];
    maskLayer2.frame = bounds2;
    maskLayer2.path = maskPath2.CGPath;
    maskLayer2.shadowRadius = 2;
    maskLayer2.shadowOpacity = 0.1;

    maskLayer2.shadowColor =[UIColor blackColor].CGColor;
    maskLayer2.fillColor = [UIColor colorWithRed:252/256.0 green:252/256.0 blue:252/256.0 alpha:1].CGColor;
    maskLayer2.shadowOffset = CGSizeMake(0, 1);


    [cell.backgroundMessageView.layer insertSublayer:maskLayer2 atIndex:0];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接