如何控制阴影扩散和模糊? [英] How to control shadow spread and blur?

查看:18
本文介绍了如何控制阴影扩散和模糊?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在草图中设计了 UI 元素,其中一个具有模糊 1 和传播 0 的阴影.我查看了文档中的视图图层属性,图层没有任何名为传播或模糊的内容,或任何等效的内容(唯一的控制只是 shadowOpacity).如何控制模糊和扩散之类的东西?

I have designed UI elements in sketch, and one of them has a shadow with blur 1 and spread 0. I looked at the doc for the views layer property and layer doesn't have anything named spread or blur, or anything equivalent (the only control was merely shadowOpacity). How can control things like blur and spread?

这是我在 Sketch 中的设置:

Here are my settings in Sketch:

这是我希望我的影子的样子:

And here is what I want my shadow to look like:

这是现在的样子:

注意,你必须点击图片才能看到阴影.

Note, you have to click on the picture to actually see the shadow.

我的代码如下:

func setupLayer(){
    view.layer.cornerRadius = 2
    view.layer.shadowColor = Colors.Shadow.CGColor
    view.layer.shadowOffset = CGSize(width: 0, height: 1)
    view.layer.shadowOpacity = 0.9
    view.layer.shadowRadius = 5
}

推荐答案

以下是如何以近乎完美的精度将所有 6 个 Sketch 阴影属性应用于 UIView 的图层:

Here's how to apply all 6 Sketch shadow properties to a UIView's layer with near perfect accuracy:

extension CALayer {
  func applySketchShadow(
    color: UIColor = .black,
    alpha: Float = 0.5,
    x: CGFloat = 0,
    y: CGFloat = 2,
    blur: CGFloat = 4,
    spread: CGFloat = 0)
  {
    masksToBounds = false
    shadowColor = color.cgColor
    shadowOpacity = alpha
    shadowOffset = CGSize(width: x, height: y)
    shadowRadius = blur / 2.0
    if spread == 0 {
      shadowPath = nil
    } else {
      let dx = -spread
      let rect = bounds.insetBy(dx: dx, dy: dx)
      shadowPath = UIBezierPath(rect: rect).cgPath
    }
  }
}

假设我们要表示以下内容:

Say we want to represent the following:

您可以通过以下方式轻松实现:

You can easily do this via:

myView.layer.applySketchShadow(
  color: .black, 
  alpha: 0.5, 
  x: 0, 
  y: 0, 
  blur: 4, 
  spread: 0)

或更简洁:

myView.layer.applySketchShadow(y: 0)

示例:

左:iPhone 8 UIView 截图;右:草图矩形.

注意:

  • 当使用非零 spread 时,它会根据 CALayer 的 bounds 对路径进行硬编码.如果图层的边界发生变化,您需要再次调用 applySketchShadow() 方法.
  • When using a non-zero spread, it hardcodes a path based on the bounds of the CALayer. If the layer's bounds ever change, you'd want to call the applySketchShadow() method again.

这篇关于如何控制阴影扩散和模糊?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆