gpt4 book ai didi

ios - 向形状已被 UIBezierPath 更改的 UIView 添加阴影

转载 作者:搜寻专家 更新时间:2023-11-01 06:11:47 28 4
gpt4 key购买 nike

我为 UIView 创建了一个扩展,它允许我制作一个凹形。

extension UIView {
func createConcave(depth: CGFloat) {
let width = self.bounds.width
let height = self.bounds.height

let path = UIBezierPath()
let p0 = CGPoint(x: 0, y: 0)
let p2 = CGPoint(x: width, y: 0)
let p1 = CGPoint(x: width / 2, y: depth)
path.move(to: p0)
path.addQuadCurve(to: p2, controlPoint: p1)
path.addLine(to: CGPoint(x: width, y: height))
path.addLine(to: CGPoint(x: 0, y: height))
path.addLine(to: p0)
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
self.layer.masksToBounds = false
}
}

The shape of the UIView after implementing concavity

在与形状相匹配的 View 中添加阴影的好的解决方案是什么?我是否必须将阴影路径指定为与凹形相同的路径?

最佳答案

您正在将图层遮盖到路径。因此,任何东西,包括阴影,都会被该蒙版剪裁。

不是 mask ,而是添加子层。

例如

@IBDesignable
class ConcaveView: UIView {
@IBInspectable var depth: CGFloat = 10 { didSet { updatePath() } }
@IBInspectable var fillColor: UIColor = .red { didSet { shapeLayer.fillColor = fillColor.cgColor } }

private lazy var shapeLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = fillColor.cgColor
shapeLayer.shadowColor = UIColor.black.cgColor
shapeLayer.shadowRadius = 5
shapeLayer.shadowOpacity = 1
shapeLayer.shadowOffset = .zero
return shapeLayer
}()

override init(frame: CGRect = .zero) {
super.init(frame: frame)
configure()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}

func configure() {
layer.addSublayer(shapeLayer)
clipsToBounds = false
}

override func layoutSubviews() {
super.layoutSubviews()
updatePath()
}

func updatePath() {
let path = UIBezierPath()
let point0 = CGPoint(x: bounds.minX, y: bounds.minY)
let point2 = CGPoint(x: bounds.maxX, y: bounds.minY)
let point1 = CGPoint(x: bounds.width / 2, y: bounds.minY + depth)
path.move(to: point0)
path.addQuadCurve(to: point2, controlPoint: point1)
path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
path.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY))
path.addLine(to: point0)

shapeLayer.path = path.cgPath
}
}

产生:

enter image description here

关于ios - 向形状已被 UIBezierPath 更改的 UIView 添加阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54837171/

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