带有渐变和阴影的UIView

时间:2019-02-06 03:35:33

标签: swift cagradientlayer shadowpath

尝试在UIView上添加渐变,添加圆角并添加阴影。我可以使用它,但是没有正确放置渐变。 (应替换所有红色)

let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor(red: 0.333, green: 0.376, blue: 0.498, alpha: 1.00).cgColor, UIColor(red: 0.200, green: 0.247, blue: 0.369, alpha: 1.00).cgColor]
gradientLayer.startPoint = CGPoint(x: 0, y: 0)
gradientLayer.endPoint = CGPoint(x: 1, y: 0.75)
gradientLayer.frame = self.viewBg.bounds
//self.viewBg.layer.insertSublayer(gradientLayer, at: 0) 


self.viewBg.layer.cornerRadius = 10
self.viewBg.layer.shadowColor = UIColor.black.cgColor
self.viewBg.layer.shadowOffset = CGSize(width: 7, height: 7)
self.viewBg.layer.shadowRadius = 10
self.viewBg.layer.shadowOpacity = 1

let inset: CGFloat = bounds.width * 0.05
self.viewBg.layer.shadowPath = UIBezierPath(roundedRect: bounds.insetBy(dx: inset, dy: 0.0), cornerRadius: 10).cgPath

没有注释行: enter image description here

在注释行中: enter image description here

1 个答案:

答案 0 :(得分:0)

尝试一下可能对您有帮助

extension UIView {

func setGradientBackground() {
    let colorTop =  UIColor(red:0.87, green:0.25, blue:0.30, alpha:1.0)
    let colorBottom = UIColor(red:0.95, green:0.37, blue:0.34, alpha:0.6)

    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = [colorTop.cgColor, colorBottom.cgColor]
    gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0)
    gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.0)
    gradientLayer.frame = self.bounds
    gradientLayer.cornerRadius = 20
    self.layer.shadowOffset = CGSize(width: 0, height: 2)
    self.layer.shadowOpacity = 0.3
    self.layer.shadowRadius = 3.0
    self.layer.shadowColor = UIColor.black.cgColor
    self.layer.masksToBounds = false

    self.layer.insertSublayer(gradientLayer, at: 0)

    }
}

使用

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    DispatchQueue.main.async {
        self.btnLogin.setGradientBackground()
    }
}