swift - 带渐变和阴影的 UIView

标签 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

最佳答案

试试这个也许会对你有帮助

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()
    }
}

关于swift - 带渐变和阴影的 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54546268/

相关文章:

ios - Swift 不在 CAGradientLayer 上调用类 init 方法

ios - 渐变层不在正确的位置

swift - 减慢 CAGradientLayer 动画速度

ios - UIView的shadowpath颜色没有改变

ios - 如何使用 SwiftyJSON 解析字符串数组?

ios - 'swap' 函数 Swift 之后文本变回原始文本

swift - 使用函数停用 viewdidload 中声明的 nslayoutconstraint

ios - 无法在 collectionView 中打印来自 api 的响应

ios - 有没有办法获取 UILabel 文本的 shadowPath?