【问题标题】:How to show a gradient diagonally in a view如何在视图中对角线显示渐变
【发布时间】:2019-07-03 08:07:10
【问题描述】:

我正在从 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,因为它对角线向下右下角。

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

谢谢

【问题讨论】:

    标签: ios swift uiimage uikit gradient


    【解决方案1】:

    只需将startPointendPoint 添加到渐变层:

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

    【讨论】:

    • 效果很好....谢谢....虽然我稍微调整了XY 值以使其完全符合我的要求。但是是的,这就是解决方案。
    • 同意@André Slotta。但是应该调整参数以适应问题: gradientLayer.startPoint = .init(x: 0.5, y: 1.0) , gradientLayer.endPoint = .init(x: 0.5, y: 0.0)
    • 我不明白你的评论,@YunCHEN。不应该是左上角 -> 右下角是(0,0) -> (1,1)
    • @AndréSlotta,根据截图,gradientLayer的起始位置是x:0.5,y:0.0。表示从中上到中下。
    • 对,@YunCHEN。但截图并没有显示作者想要实现的目标。所以我不确定为什么有人认为你的评论是正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    相关资源
    最近更新 更多