带阴影的 UIView,仅圆顶角和遮罩底边

UIView with shadow, rounded only top corners and masked bottom edge

我正在努力实现只会使顶角变圆并在其周围形成阴影的视图。整个视图应该被父视图遮盖在底部,以防止阴影重叠在子视图之后(阴影偏移应为 (0, 0))。

当我使用:

    // Adding shadow
    let contentSubviewLayer = contentSubview.layer
    contentSubviewLayer.masksToBounds = false
    contentSubviewLayer.shadowOpacity = 0.3
    contentSubviewLayer.shadowRadius = 2.5
    contentSubviewLayer.shadowOffset = CGSizeMake(0, 0)
    contentSubviewLayer.cornerRadius = 5.0
    contentSubviewLayer.shadowPath = UIBezierPath(rect: contentSubview.bounds).CGPath
    self.layer.masksToBounds = true

我得到:

但在添加底边遮罩后:

    // Adding maskView to round only top corners
    let maskLayer = CAShapeLayer()
    maskLayer.frame = self.contentSubview.bounds
    let roundedPath = UIBezierPath(roundedRect: maskLayer.bounds, byRoundingCorners: [UIRectCorner.TopLeft, UIRectCorner.TopRight], cornerRadii: CGSizeMake(CORNER_RADIUS, CORNER_RADIUS))
    maskLayer.fillColor = UIColor.whiteColor().CGColor
    maskLayer.backgroundColor = UIColor.clearColor().CGColor
    maskLayer.path = roundedPath.CGPath
    contentSubview.layer.mask = maskLayer

我得到:

所需的效果应该是上述两者的结合,并且应该类似于这样的效果,左、上和右边缘周围有阴影

请帮忙! 提前谢谢你。

我倾向于使用一个名为 PaintCode 的应用来生成我需要的 Swift 代码来处理这类事情。我最近做了类似的事情,它为我吐了出来:

let context = UIGraphicsGetCurrentContext()

    //// Color Declarations
    let chiesi_light_grey = UIColor(red: 0.851, green: 0.851, blue: 0.851, alpha: 1.000)

    //// Shadow Declarations
    let chiesi_shadow = NSShadow()
    chiesi_shadow.shadowColor = chiesi_light_grey.colorWithAlphaComponent(0.8 * CGColorGetAlpha(chiesi_light_grey.CGColor))
    chiesi_shadow.shadowOffset = CGSize(width: 0.1, height: 4.1)
    chiesi_shadow.shadowBlurRadius = 2

    //// Rectangle Drawing
    let rectanglePath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 50, height: 54), byRoundingCorners: [UIRectCorner.BottomLeft, UIRectCorner.BottomRight], cornerRadii: CGSize(width: 8, height: 8))
    rectanglePath.closePath()
    CGContextSaveGState(context)
    CGContextSetShadowWithColor(context, chiesi_shadow.shadowOffset, chiesi_shadow.shadowBlurRadius, (chiesi_shadow.shadowColor as! UIColor).CGColor)
    UIColor.whiteColor().setFill()
    rectanglePath.fill()
    CGContextRestoreGState(context)

    chiesi_light_grey.setStroke()
    rectanglePath.lineWidth = 2
    rectanglePath.stroke()

也许对你有帮助。