gpt4 book ai didi

ios - 渐变层在 iOS 中不起作用

转载 作者:行者123 更新时间:2023-11-28 14:59:44 25 4
gpt4 key购买 nike

我有制作渐变的代码,但它根本没有显示。如果我更改包含该渐变的 View 颜色,我就能看到它。所以 View 很好,只是渐变有一些问题。这是我的代码:

class KolodaCardView: UIView {
var helloWorld = "Hello World"
var userImage = UIImageView()
var userName = UILabel()
var parent = UIView()
var gradient = CAGradientLayer()
var gradientView = UIView()

override init(frame: CGRect) {
super.init(frame: frame)
parent = self
parent.backgroundColor = .clear
parent.layer.cornerRadius = 16
parent.clipsToBounds = true

setupUserImage()
setupUserName()
}

override func layoutSubviews() {
super.layoutSubviews()
gradient.frame = gradientView.frame
}

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

func setupUserImage() {
parent.addSubview(userImage)
userImage.snp.makeConstraints { make in
make.top.equalTo(parent)
make.bottom.equalTo(parent)
make.left.equalTo(parent)
make.right.equalTo(parent)
}
userImage.contentMode = .scaleAspectFill
userImage.clipsToBounds = true
userImage.layer.cornerRadius = 16

userImage.addSubview(gradientView)
gradientView.snp.makeConstraints { (make) in
make.bottom.equalToSuperview()
make.left.equalToSuperview()
make.right.equalToSuperview()
make.height.equalTo(60)
}
// gradientView.backgroundColor = .green
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 0, y: 1)
gradient.locations = [0.5,1.0]
gradient.frame = gradientView.bounds
gradient.colors = [UIColor.red.cgColor, UIColor.yellow.cgColor]
gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
gradientView.layer.insertSublayer(gradient, at: 0)
}

func setupUserName() {
parent.addSubview(userName)
userName.snp.makeConstraints { (make) in
make.left.equalTo(parent).offset(16)
make.right.equalTo(parent)
make.height.equalTo(20)
make.bottom.equalTo(-20)
}
userName.textColor = .black
userName.textAlignment = .left
}
}

我在这里检查了几个解决方案,但没有任何效果!有人可以检查我是否忽略了什么吗?

enter image description here

最佳答案

在渐变中,您必须提供渐变颜色的位置,以从起点到终点填充图层。

gradientLayer.startPoint = CGPoint(x: 0, y: 0)
gradientLayer.endPoint = CGPoint(x: 0, y: 1)
gradientLayer.colors = [UIColor.red.cgColor ,UIColor.yellow.cgColor]
gradientLayer.locations = [0.5,1.0]
your_gradientView.layer.insertSublayer(gradientLayer, at: 0)

关于ios - 渐变层在 iOS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49027224/

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