如何在视图中沿对角线显示渐变

How to show a gradient diagonally in a view

我正在从 2 UIColors 生成一个 gradient,然后使用这些函数从中生成一个 UIImage

//Function to generate the UIImage from 2 colors.
func createGradient(color1: UIColor, color2: UIColor) -> UIImage {
    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = self.view.bounds
    gradientLayer.colors = [color1.cgColor, color2.cgColor]
    let image = image(from: gradientLayer)
    return image
}

//Function to generate an Image from a CALayer.
func image(from layer: CALayer) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, true, 0)
    layer.render(in: UIGraphicsGetCurrentContext()!)
    let outputImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return outputImage ?? UIImage()
}

我的结果是这样的

但我想从左上角到右下角以对角线显示...所以 Red 应该从左上角开始逐渐淡入 Yellow当它向右下角倾斜下降时。

我不确定是否应该对角生成渐变,或者我是否应该在生成图像后旋转图像以对角显示它。

谢谢

只需将startPointendPoint添加到渐变层:

[...]
gradientLayer.startPoint = .init(x: 0, y: 0) // top left
gradientLayer.endPoint = .init(x: 1, y: 1) // bottom right
[...]