代码之家  ›  专栏  ›  技术社区  ›  IOS

对于Uiimageview,如何在ios swift4中将CGgradient背景色设置为背景色?

  •  0
  • IOS  · 技术社区  · 7 年前
    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)
    

    它不工作。。。如何使用cgradient图像背景颜色?

    1 回复  |  直到 7 年前
        1
  •  0
  •   vp2698    7 年前

    您可以从渐变创建图像并将其设置为 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!
    }