ios - 如何在 View 中沿对角线显示渐变

标签 ios swift uiimage uikit gradient

我正在从 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()
}

我的结果是这样的

enter image description here

但我想从左上角到右下角以对角线显示这个......所以 Red 应该从左上角开始逐渐淡入 Yellow 因为它沿对角线向下朝向右下角。

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

谢谢

最佳答案

只需将 startPointendPoint 添加到渐变层即可:

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

关于ios - 如何在 View 中沿对角线显示渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56865609/

相关文章:

ios - 如何为 aspect fit 模式设置圆角的 UIImageView

ios - 在左上角位置的边框上带有标签的 TextField

ios - 堆栈 View ScaleAspectFit 蒙版在 Swift 中调整大小

ios - 表didSelect方法无法正常工作

ios - ARKit 如何从角落而不是中心绘制平面

ios - 通过 Cocoapods 包含 Xcode 7 UI 测试依赖项?

ios - 如何直接在 iOS 应用程序中存储和使用 MP4 文件

ios - AdMob 横幅覆盖底部工具栏

c# - UIImageView.Image 使用 MonoTouch 发送邮件附件

ios - 使用泛光填充在 UIImage 中填充颜色时出错