gpt4 book ai didi

ios - 创建带有透明孔的 CAGradient 图层?

转载 作者:行者123 更新时间:2023-11-28 12:14:01 37 4
gpt4 key购买 nike

目前我是这样做的:

final class BorderedButton: BottomNavigationButton {

private let gradient = CAGradientLayer()
private let shapeLayer = CAShapeLayer()

override func layoutSubviews() {
super.layoutSubviews()

let radius = bounds.size.height / 2
let outside = UIBezierPath(roundedRect: CGRect(x: 0.0, y: 0.0, width: bounds.width, height: bounds.height), cornerRadius: radius)
let inside = UIBezierPath(roundedRect: CGRect(x: 3.0, y: 3.0, width: bounds.width - 6, height: bounds.height - 6), cornerRadius: radius - 3)
outside.append(inside)
outside.usesEvenOddFillRule = true
shapeLayer.path = outside.cgPath
}

init(color: UIColor?) {
super.init(frame: .zero)

let isGradient = color == nil

shapeLayer.fillRule = kCAFillRuleEvenOdd
shapeLayer.fillColor = UIColor.red.cgColor
layer.insertSublayer(shapeLayer, at: 0)
//gradient part
gradient.colors = isGradient ? [Constants.gradientStart, Constants.gradientEnd] : [color!.cgColor, color!.cgColor]
gradient.startPoint = CGPoint(x: 0.2, y: 0.5)
gradient.endPoint = CGPoint(x: 1, y: 1)
}
}

如何将渐变应用于我的代码?

最佳答案

不要将 CAShapeLayer 添加到 View 的 layer,而是将其设置为 CAGradientLayermask >。也不要忘记设置渐变层的边界。

我必须进行一些修改才能让它在 Playground 上运行,但这对我有用:

let gradientStart = UIColor.orange
let gradientEnd = UIColor.blue

final class BorderedButton: UIButton {

private let gradient = CAGradientLayer()
private let shapeLayer = CAShapeLayer()

override func layoutSubviews() {
super.layoutSubviews()

let radius = bounds.size.height / 2
let outside = UIBezierPath(roundedRect: CGRect(x: 0.0, y: 0.0, width: bounds.width, height: bounds.height), cornerRadius: radius)
let inside = UIBezierPath(roundedRect: CGRect(x: 3.0, y: 3.0, width: bounds.width - 6, height: bounds.height - 6), cornerRadius: radius - 3)
outside.append(inside)
outside.usesEvenOddFillRule = true
shapeLayer.path = outside.cgPath
gradient.frame = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height)
}

init(color: UIColor?, frame: CGRect = .zero) {
super.init(frame: frame)

let isGradient = color == nil

shapeLayer.fillRule = kCAFillRuleEvenOdd

//gradient part
gradient.colors = isGradient ? [gradientStart.cgColor, gradientEnd.cgColor] : [color!.cgColor, color!.cgColor]
gradient.startPoint = CGPoint(x: 0.2, y: 0.5)
gradient.endPoint = CGPoint(x: 1, y: 1)

gradient.mask = shapeLayer

layer.addSublayer(gradient)
}

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

关于ios - 创建带有透明孔的 CAGradient 图层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47468383/

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