如何在iOS中创建从全彩色到不透明度0的渐变?

时间:2019-06-14 20:59:09

标签: ios swift gradient opacity

我有looked here,但是根据我在下面尝试并显示的示例,该方法无法正常工作。它无法完成以下任务。我正在寻找创建一个从全黑到不全为0的全黑的渐变:

enter image description here

@IBDesignable
final class GradientView: UIView {
    @IBInspectable var startColor: UIColor = UIColor.clear
    @IBInspectable var endColor: UIColor = UIColor.clear

    override func draw(_ rect: CGRect) {
        let gradient: CAGradientLayer = CAGradientLayer()
//        gradient.frame = bounds
        gradient.frame = CGRect(x: CGFloat(0),
                                y: CGFloat(0),
                                width: superview!.frame.size.width,
                                height: superview!.frame.size.height)
        gradient.colors = [startColor.cgColor, endColor.cgColor]
        gradient.zPosition = -1
        layer.addSublayer(gradient)
    }
}

如何才能做到这一点,最好是在界面生成器中实现?

2 个答案:

答案 0 :(得分:1)

以下是我的实现

@IBDesignable
final class GradientView: UIView {
    override func draw(_ rect: CGRect) { 
        //// General Declarations
        let context = UIGraphicsGetCurrentContext()!


        //// Gradient Declarations
        let gradient = CGGradient(colorsSpace: nil, colors: [UIColor.white.cgColor, 
     UIColor.white.blended(withFraction: 0.5, of: UIColor.black).cgColor, 
    UIColor.black.cgColor] as CFArray, locations: [0, 0.51, 0.89])!

    //// Rectangle Drawing
    let rectangleRect = CGRect(x: frame.minX + 11, y: frame.minY + 8, width: 85, height: 54)
    let rectanglePath = UIBezierPath(rect: rectangleRect)
    context.saveGState()
    rectanglePath.addClip()
    context.drawLinearGradient(gradient,
        start: CGPoint(x: rectangleRect.midX, y: rectangleRect.minY),
        end: CGPoint(x: rectangleRect.midX, y: rectangleRect.maxY),
        options: [])
    context.restoreGState()
    }
}

答案 1 :(得分:1)

我最终要做的事情如下:

  private func setupGradient() { 

    //Below for container
    gradientViewContainer.frame = CGRect(x: 0, y: 152, width: 117, height: 38) 
    gradientViewContainer.isHidden = true

    //Below for actual gradient
    gradientLayer.frame = CGRect(x: 0, y: 152, width: gradientViewContainer.frame.width, height: gradientViewContainer.frame.height)

    gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.0)
    gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)

    gradientLayer.colors = [UIColor.black.withAlphaComponent(0.0).cgColor, UIColor.black.withAlphaComponent(0.7).cgColor, UIColor.black.withAlphaComponent(0.7).cgColor,  UIColor.black.withAlphaComponent(1.0).cgColor]
    gradientLayer.locations = [0.0, 1.0]

    gradientViewContainer.layer.insertSublayer(gradientLayer, at: 0)
    gradientViewContainer.alpha = 0.65

}

然后在viewDidLoad中:

    setupGradient()
    myView.layer.addSublayer(gradientLayer)