如何在蒙面的UIView周围画出阴影?

时间:2017-05-09 17:32:01

标签: ios objective-c uiview uibezierpath cashapelayer

我想制作一个UIView形状,如图1 。并且还应该在我的视角周围留下阴影。

enter image description here

我使用下面的代码与CAShaperLayer

一起绘制UIBezierPath
 UIBezierPath *bezier = [UIBezierPath bezierPath];
  [bezier moveToPoint:CGPointMake(0,7)];
  [bezier addLineToPoint:CGPointMake(self.menuView.frame.size.width-15, 7)];
  [bezier addLineToPoint:CGPointMake(self.menuView.frame.size.width-10,0)];
  [bezier addLineToPoint:CGPointMake(self.menuView.frame.size.width-5, 7)];
  [bezier addLineToPoint:CGPointMake(self.menuView.frame.size.width, 7)];
  [bezier addLineToPoint:CGPointMake(self.menuView.frame.size.width, self.menuView.frame.size.height)];
  [bezier addLineToPoint:CGPointMake(0, self.menuView.frame.size.height)];
  [bezier closePath];

   CAShapeLayer *maskLayer = [CAShapeLayer layer];
   maskLayer.path = [bezier CGPath];

  self.menuView.layer.mask = maskLayer;

并添加阴影

self.menuView.layer.shadowColor = [[UIColor colorWithRed:8.0f/255.0f green:37.0f/255.0f blue:82.0f/225.0f alpha:1] CGColor];
    self.menuView.layer.shadowOffset = CGSizeZero;
    self.menuView.layer.shadowOpacity = 0.3f;
    self.menuView.layer.shadowRadius = 5.0f;
    self.menuView.layer.masksToBounds=NO;

我的问题

在menuView上屏蔽CAShaperLayer后,阴影消失了。 图2

enter image description here

我还尝试在其上添加Sublayer而不是Masking View

[self.menuView.layer addSublayer:maskLayer]

但这会隐藏我所有SubViews的MenuView 图3

(我已将CASahperLayer颜色更改为黑色只是为了显示)

enter image description here

我的问题是

图1 ???所示,使用阴影获得完美形状的最佳方法是什么?

(提前致谢)

1 个答案:

答案 0 :(得分:-1)

extension UIView{

    func viewShadowBorder()  {
        self.layer.shadowColor = UIColor.gray.cgColor
        self.layer.shadowOpacity = 1
        self.layer.shadowOffset = CGSize.zero
        self.layer.shadowRadius = 2
        self.layer.cornerRadius = 2
    }
    }