UIView阴影渐变

UIView Shadow Gradient

我在我的 iOS 项目中创建了一个自定义 UIView,它有一个投影。 我的目标是对视图背景上的阴影应用相同的渐变。

下面是我当前纯色阴影的示例。

这是通过 UIView 的子类使用以下代码完成的:

override func layoutSubviews() {
    let gradientLayer = layer as! CAGradientLayer
    gradientLayer.colors = [topColor.cgColor, bottomColor.cgColor]
    gradientLayer.startPoint = CGPoint(x: startPointX, y: startPointY)
    gradientLayer.endPoint = CGPoint(x: endPointX, y: endPointY)
    layer.cornerRadius = cornerRadius
    layer.shadowColor = shadowColor.cgColor
    layer.shadowOffset = CGSize(width: shadowX, height: shadowY)
    layer.shadowRadius = shadowBlur
    layer.shadowOpacity = 1

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

我一直在尝试创建第二个渐变图层并将其遮盖到阴影中,但没有成功。请给我指明正确的方向!

我认为你不能用标准的 CALayer 阴影做更多的事情。 看看 CALayer 的 filters 属性.

https://developer.apple.com/documentation/quartzcore/calayer/1410901-filters

创建第二个 CAGradientLayer 并应用 GausianBlur 过滤器。

https://developer.apple.com/library/content/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/filter/ci/CIGaussianBlur

禁用标准图层阴影并将模糊图层添加为子图层。

我相信@jacek 是对的,你正在突破你可以用 CALayer 阴影做的事情的极限(老实说,这并不多)

正如 jacek 所解释的那样,最好的办法是创建自己的阴影,尽管另一个 CAGradientLayer 应用高斯模糊来充当阴影。

此外,我认为将您的代码放在 layoutSubviews 中不是最合适的位置。一旦配置好你的层就不需要改变太多,因此如果你的布局改变很多,它会被调用很多。

通常,如果使用来自界面构建器的视图,我会在专用 configureBackgroundViews 函数中从 awakeFromNib 调用此逻辑。

使用我的代码满足你在我的 gitRepo 中可用的要求 https://github.com/Krishnarjun-Banoth/BlurView/tree/master/Shadows

第 1 步:只需将 BlurEffect.swift 文件拖放到您的项目中。

第 2 步:然后只需对每个视图分别使用下面的视图扩展方法。

  testView.applyGradient(colours: [UIColor.blue,UIColor.orange]) //pass your required colours.
  testView.blur(blurRadius: 5.0)

注意:灵感来自@Jacek Głazik 的回答和 FlexMonkey 的教程。