我创建了一个包含渐变的视图,但渐变不适用于整个图像/视图。在iPhone plus设备中通常会出现此问题。
import UIKit
class MainViewController: UIViewController {
@IBOutlet weak var imageViewBanner: UIImageView!
@IBOutlet weak var viewGradient: UIView!
let color1 = UIColor(red: 48.0/255.0, green: 178.0/255.0, blue: 166.0/255.0, alpha: 1.0)
let color2 = UIColor(red: 82.0/255.0, green: 96.0/255.0, blue: 169.0/255.0, alpha: 1.0)
override func viewDidLoad() {
super.viewDidLoad()
self.viewGradient.frame = self.viewGradient.bounds
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [color1.cgColor, color2.cgColor]
gradientLayer.locations = [0.0 , 1.0]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.viewGradient.frame.size.height)
self.viewGradient.layer.insertSublayer(gradientLayer, at: 0)
}
}
答案 0 :(得分:3)
gradientLayer.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.viewGradient.frame.size.height)
在viewDidLayoutSubviews
答案 1 :(得分:1)
这是完整的代码代码段
override func viewDidLayoutSubviews() {
self.viewGradient.frame = self.viewGradient.bounds
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [color1.cgColor, color2.cgColor]
gradientLayer.locations = [0.0 , 1.0]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.frame = CGRect(x: 0.0, y: 0.0, width: self.viewGradient.frame.size.width, height: self.viewGradient.frame.size.height)
self.viewGradient.layer.insertSublayer(gradientLayer, at: 0)
}
答案 2 :(得分:0)
override func layoutSubviews() {
super.layoutSubviews()
DispatchQueue.main.async {
self.yourView.layer.sublayers?[0].frame = self.yourView.bounds
}
}