0

gradient从 2UIColors生成一个,然后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

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

谢谢

4

1 回答 1

4

只需将startPointand添加endPoint到渐变层:

[...]
gradientLayer.startPoint = .init(x: 0, y: 0) // top left
gradientLayer.endPoint = .init(x: 1, y: 1) // bottom right
[...]
于 2019-07-03T08:13:56.250 回答