UIView阴影不可见

时间:2019-04-26 13:18:48

标签: swift

我有一个叫float intensity = smoothstep(1.0, 0.0, ratio);的{​​{1}}。

在创建UIView并将其添加到主视图之后,我正在尝试添加一些阴影。我的代码:

UIView

生成阴影的代码:

containerView

2 个答案:

答案 0 :(得分:1)

这应该有帮助:

extension UIView {

    func addShadow(withOpacity opacity:Float, radius:CGFloat, andColor color:UIColor) {
         self.layer.shadowColor         = color.cgColor
         self.layer.shadowOffset        = CGSize(width:-1.0, height:1.0)
         self.layer.shadowOpacity       = opacity
         self.layer.shadowRadius        = radius
    }
}

示例:

containerView.addShadow(withOpacity: 0.4, radius: 0.4, andColor: .black)

答案 1 :(得分:1)

需要注意的几点:

  • 请确保您的容器视图不太靠近屏幕的左侧或底部,因为阴影将显示在容器视图的左侧和下方。

  • 请确保对阴影路径使用 rounded 矩形,因为容器视图的拐角半径非零。

  • 如果仍然看不到阴影,请尝试增加阴影偏移。

您可以将此代码复制并粘贴到操场上并打开实时视图:

extension UIView {

    func dropShadow(scale: Bool = true) {
        layer.masksToBounds = false
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.5
        layer.shadowOffset = CGSize(width: -5, height: 5) // I made this larger
        layer.shadowRadius = 1

        // I used a rounded rect here
        layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.layer.cornerRadius).cgPath
        layer.shouldRasterize = true
        layer.rasterizationScale = scale ? UIScreen.main.scale : 1
    }
}

let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = .white
let containerView = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))

let bg_clear = UIColor.green
containerView.backgroundColor = bg_clear


containerView.layer.cornerRadius =  15
containerView.clipsToBounds = false

containerView.dropShadow() // Generate Shadow

view.addSubview(containerView)

PlaygroundPage.current.liveView = view

您应该看到:

enter image description here