UIView Shadow Gradient

时间:2017-09-27 10:41:59

标签: ios swift uiview gradient shadow

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

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

Shadow Example 这是通过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
}

我一直在玩创建第二个渐变层并将其遮盖到阴影但却没有运气。请指出我正确的方向!

3 个答案:

答案 0 :(得分:4)

我认为您无法使用标准CALayer阴影做更多事情。 请查看CALayer的过滤器属性。

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

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

答案 1 :(得分:0)

我相信@jacek是对的,你正在推动使用CALayer阴影所做的事情的限制(说实话并不多)

jacek解释的最好的事情是创建自己的阴影,尽管另一个CAGradientLayer应用高斯模糊作为阴影。

另外,我不相信将代码放在layoutSubviews内是最合适的地方。配置完成后,您的图层不需要进行太多更改,因此如果您的布局发生很大变化,它会被调用很多。

通常,如果使用来自interface-builder的视图,我会在专用的awakeFromNib函数中从configureBackgroundViews调用此逻辑。

答案 2 :(得分:0)

根据我的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)

注意:灵感来自@JacekGłazik的答案和FlexMonkey的教程。