gpt4 book ai didi

swift - 将圆角半径设置为负值以实现凹角

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

我使用这段代码来圆化 UIView 的角:

extension UIView {

func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
self.layer.masksToBounds = false
}
}

然后我使用了 view.roundCorners([.topLeft, .topRight], radius: view.frame.width/3)

现在这个圆角是凸的,我想要相反的。这意味着顶角将保持在相同的点,但它们之间的线向 View 内部变圆。我尝试通过使用负值调用上述函数来实现此目的,但这导致什么也没有发生。

我添加了一张图片来证明我的目标。我怎么能做到这一点? enter image description here

最佳答案

您需要创建自己的 UIBezierPath。对于凹端,addQuadCurve(to:controlPoint:) 派上用场。

这里我使用参数 depth 来控制曲线的数量:

extension UIView {

func concaveEnds(depth: CGFloat) {
let width = self.bounds.width
let height = self.bounds.height

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

Playground 演示:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 100))
view.backgroundColor = .red

view.concaveEnds(depth: 0.4)

Demo in Playground Demo with less curve

关于swift - 将圆角半径设置为负值以实现凹角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47496924/

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