Swift UIView阴影不可见
我有一个名为Swift UIView阴影不可见,swift,Swift,我有一个名为containerView的ui视图 创建UIView并将其添加到主视图后,我尝试添加一点阴影。我的代码: let containerView = UIView() let bg_clear = UIColor(hexString: "#34495E") containerView.backgroundColor = bg_clear containerView.layer.cornerRadius = 15 containerView
containerView
的ui视图
创建UIView并将其添加到主视图后,我尝试添加一点阴影。我的代码:
let containerView = UIView()
let bg_clear = UIColor(hexString: "#34495E")
containerView.backgroundColor = bg_clear
containerView.layer.cornerRadius = 15
containerView.clipsToBounds = false
containerView.dropShadow() // Generate Shadow
view.addSubview(containerView)
containerView.translatesAutoresizingMaskIntoConstraints = false
containerView.heightAnchor.constraint(equalToConstant: 50).isActive = true
containerView.widthAnchor.constraint(equalToConstant: 300).isActive = true
containerView.centerXAnchor.constraint(equalTo: tabBar.centerXAnchor).isActive = true
生成阴影的代码:
extension UIView {
func dropShadow(scale: Bool = true) {
layer.masksToBounds = false
layer.shadowColor = UIColor(hexString: "#000000").cgColor
layer.shadowOpacity = 0.5
layer.shadowOffset = CGSize(width: -1, height: 1)
layer.shadowRadius = 1
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = scale ? UIScreen.main.scale : 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)
需要注意的几点:
- 确保容器视图不太靠近屏幕的左侧或底部,因为阴影将显示在容器视图的左侧和下方
- 确保阴影路径使用圆角矩形,因为容器视图的角半径非零
- 如果仍然看不到阴影,请尝试增加阴影偏移
您可以将此代码复制并粘贴到游乐场中,然后打开live view:
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
你应该看到: