首页 > 解决方案 > 如何在iOS中创建从全色到不透明度为0的渐变?

问题描述

看过这里,但根据他们的例子,我试过并在下面展示,没有用。它无法完成以下任务。我正在寻找从全黑到不透明度为 0 的全黑的渐变:

在此处输入图像描述

@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)
    }
}

我怎样才能做到这一点,最好是在界面构建器中?

标签: iosswiftgradientopacity

解决方案


以下是我的实现

@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()
    }
}

推荐阅读