gpt4 book ai didi

ios - 在 UIView 顶部添加内部阴影

转载 作者:IT王子 更新时间:2023-10-29 05:15:13 31 4
gpt4 key购买 nike

我查了一下,但找不到如何向 UIView 添加内部阴影,只有顶部(从上到下)用于 Swift。在 Swift 中添加内圈的最佳方法是什么?

编辑:我在 SO 上找到了一些问题和答案,但它们要么在 obj-c 中,要么看起来很复杂。我只是在寻找一种更 Swifty 的方式,如果有的话

我想要实现的目标:

enter image description here

最佳答案

这是我制作的纯 Swift 版本:

public class EdgeShadowLayer: CAGradientLayer {

public enum Edge {
case Top
case Left
case Bottom
case Right
}

public init(forView view: UIView,
edge: Edge = Edge.Top,
shadowRadius radius: CGFloat = 20.0,
toColor: UIColor = UIColor.white,
fromColor: UIColor = UIColor.black) {
super.init()
self.colors = [fromColor.cgColor, toColor.cgColor]
self.shadowRadius = radius

let viewFrame = view.frame

switch edge {
case .Top:
startPoint = CGPoint(x: 0.5, y: 0.0)
endPoint = CGPoint(x: 0.5, y: 1.0)
self.frame = CGRect(x: 0.0, y: 0.0, width: viewFrame.width, height: shadowRadius)
case .Bottom:
startPoint = CGPoint(x: 0.5, y: 1.0)
endPoint = CGPoint(x: 0.5, y: 0.0)
self.frame = CGRect(x: 0.0, y: viewFrame.height - shadowRadius, width: viewFrame.width, height: shadowRadius)
case .Left:
startPoint = CGPoint(x: 0.0, y: 0.5)
endPoint = CGPoint(x: 1.0, y: 0.5)
self.frame = CGRect(x: 0.0, y: 0.0, width: shadowRadius, height: viewFrame.height)
case .Right:
startPoint = CGPoint(x: 1.0, y: 0.5)
endPoint = CGPoint(x: 0.0, y: 0.5)
self.frame = CGRect(x: viewFrame.width - shadowRadius, y: 0.0, width: shadowRadius, height: viewFrame.height)
}
}

required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

使用它,

let topShadow = EdgeShadowLayer(forView: targetView, edge: .Top)
targetView.layer.addSublayer(topShadow)

请注意,它默认为 20 点深的黑到白渐变。

完整的代码,以及一个示例 UIViewController,可以让您在 View 的所有四个角上切换阴影,可以在 https://github.com/jrtibbetts/Tenebrae 找到。 .我还非常详尽地记录了 EdgeShadowLayer

关于ios - 在 UIView 顶部添加内部阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37668965/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com