ios - 对于 Uiimageview 如何将 CGgradient 背景色设置为 ios swift 4 中的背景色?

标签 ios swift uiimageview gradient cagradientlayer

var navigationImageView:UIImageView! = UIImageView()
navigationImageView.frame = (0,0,320,64)

var gradient = CAGradientLayer()
let gradientDark = UIColor(red: 148/255.0, green:210/255.0, blue: 245/255.0, alpha: 1.0)
let gradientLight = UIColor(red: 222/255.0, green:247/255.0, blue: 230/255.0, alpha: 1.0)
let gradientLight1 = UIColor(red: 245/255.0, green:247/255.0, blue: 206/255.0, alpha: 1.0)
gradient.frame = navigationImageView.bounds

let color1 = gradientDark.cgColor
let color2 = gradientLight.cgColor
let color3 = gradientLight1.cgColor

gradient.colors = [color1, color2, color3]

gradient.colors = [gradientDark.cgColor,gradientLight.cgColor,gradientLight1.cgColor];

navigationImageView.layer.insertSublayer(gradient, at: 0)

它不起作用...如何使用渐变图像背景颜色?

最佳答案

您可以从渐变中制作图像并将其设置在imageView

let gradient = CAGradientLayer()
let screenWidth = UIScreen.main.bounds.size.width
let defaultNavigationBarFrame = CGRect(x: 0, y: 0, width: screenWidth, height: 64)
gradient.frame = defaultNavigationBarFrame

//colors
let gradientDark = UIColor(red: 148/255.0, green:210/255.0, blue: 245/255.0, alpha: 1.0)
let gradientLight = UIColor(red: 222/255.0, green:247/255.0, blue: 230/255.0, alpha: 1.0)
let gradientLight1 = UIColor(red: 245/255.0, green:247/255.0, blue: 206/255.0, alpha: 1.0)

gradient.colors = [gradientDark.cgColor,gradientLight.cgColor,gradientLight1.cgColor]
// Create image.
let imageBG: UIImage = self.gradientImage(fromLayer: gradient)

如果你想在导航栏中设置。

self.navigationController?.navigationBar.setBackgroundImage(imageBG,
                                                                for: .default)

从渐变创建图像。

func gradientImage(fromLayer layer: CALayer) -> UIImage {
    UIGraphicsBeginImageContext(layer.frame.size)

    layer.render(in: UIGraphicsGetCurrentContext()!)

    let outputImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    return outputImage!
}

关于ios - 对于 Uiimageview 如何将 CGgradient 背景色设置为 ios swift 4 中的背景色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48495715/

相关文章:

iphone - 移除 UINavigationController 圆角

ios - 如何将对象放置在中心图像周围的阵列中?

ios - customFooterView 内的 UISwitch 需要调用使用 Swift 声明的类外部的方法

ios - 阴影未出现在 UIImageView 下(Swift)

ios - UIImageView 重新调整大小并同时旋转 UIImageView?

ios - Apple 推送通知类服务,仅在前台运行时

ios - 如何在 Firebase 中创建自动递增键?

ios - 如何从 iOS 私有(private) api 二进制文件中获取 header 和函数?如何对应用程序进行逆向工程?

ios - 从 tableView 中选定的行打开 Map AnnotationView

iPhone UIImageView 动画问题