【问题标题】:Add shadow to selected Edges UIView为选定的边缘 UIView 添加阴影
【发布时间】:2018-09-12 14:30:09
【问题描述】:

我需要创建带有阴影的 UIView,但我只需要右、左、下边缘的阴影 -> 上边缘没有阴影。有可能这样做吗?我尝试了不同的偏移量,但我没有达到我的目标。

【问题讨论】:

  • 你的意思是你只希望阴影来自矩形的一个边缘吗?例如,阴影从底部出现,而不是从顶部或侧面出现?
  • 您可能想使用CALayer.shadowPath - 这是一篇不错的入门博文:nachbaur.com/2010/11/16/…(不是我的)

标签: ios swift uiview uikit


【解决方案1】:

这样的?

let yourView = UIView()
yourView.frame = CGRect(x: 50, y: 50, width: 100, height: 100)
yourView.backgroundColor = UIColor.blue // NEEDS A COLOR TO SHOW SHADOW
yourView.layer.shadowColor = UIColor.black.cgColor
yourView.layer.shadowOpacity = 1
yourView.layer.shadowOffset = CGSize.zero
yourView.layer.shadowRadius = 10
self.view.addSubview(yourView)

【讨论】:

    【解决方案2】:

    在我个人看来,克服后一个问题的最佳方法是创建 UIView 的@IBDesignable 扩展并声明@IBInspectable 属性,如下所述

    public extension UIView {
    
        // MARK: - Inspectables
    
        /**
         Defines the color of the shadow behind the view (defaults to nil).
         */
    
        @IBInspectable public var shadowColor: UIColor? {
            set {
                if let color = newValue {
                    self.layer.shadowColor = color.cgColor
                } else {
                    self.layer.shadowColor = nil
                }
            } get {
                if let color = layer.shadowColor {
                    return UIColor(cgColor: color)
                }
                return nil
            }
        }
    
        /**
         Defines the radius of the shadow behind the view.
         */
    
        @IBInspectable public var shadowRadius: CGFloat {
            set(newValue) {
                self.layer.shadowRadius = newValue
            } get {
                return self.layer.shadowRadius
            }
        }
    
        /**
         Defines the opacity of the shadow behind the view.
         */
    
        @IBInspectable public var shadowOpacity: Float {
            set(newValue) {
                self.layer.shadowOpacity = newValue
            } get {
                return self.layer.shadowOpacity
            }
        }
    
        /**
         Defines the offset of the shadow behind the view.
         */
    
        @IBInspectable public var shadowOffset: CGSize {
            set(newValue) {
                self.layer.shadowOffset = newValue
            } get {
                return self.layer.shadowOffset
            }
        }
    
    }
    

    之后,您将能够为情节提要中的每个 UIView(或从 UIView 继承的类)找到后面的参数。

    但是,如果您以编程方式工作,则必须尝试使用​​ shadowOffset 属性,直到获得所需的视觉效果。

    【讨论】:

      猜你喜欢
      • 2014-01-20
      • 1970-01-01
      • 2015-10-23
      • 2013-07-04
      • 2012-06-07
      • 2018-07-19
      • 2014-07-30
      • 1970-01-01
      相关资源
      最近更新 更多