向自定义 UIView 添加渐变颜色

Add gradient color to a custom UIView

我实现了自定义 UIView class 实现了一种飞人;以下代码是我用来实现 class:

import UIKit
import ChameleonFramework

class PolygonalView: UIView
{
    override init(frame: CGRect)
    {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)
    }

    override func draw(_ rect: CGRect) {

        guard let context = UIGraphicsGetCurrentContext() else { return }

        context.beginPath()
        context.move(to: CGPoint(x: rect.minX, y: rect.minY))
        context.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
        context.addLine(to: CGPoint(x: rect.maxX, y: 171))
        context.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
        context.closePath()

        context.setFillColor(FlatSkyBlue().cgColor)
        context.fillPath()
    }
}

然后在我的 UIViewController 中创建了我的视图:

let pol = PolygonalView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 196))
        pol.backgroundColor = UIColor.clear

        self.view.addSubview(pol)

我达到了我的目标,是的!但是出现了一个问题:如果我设置一个渐变,这个渐变会覆盖视图的所有矩形框。 以下代码和图片...

let gradientColor = CAGradientLayer()
        gradientColor.frame = pol.bounds
        gradientColor.colors = [FlatSkyBlue().cgColor, FlatSkyBlueDark().cgColor, FlatBlue().cgColor]
        gradientColor.startPoint = CGPoint(x: 0, y: 0)
        gradientColor.endPoint = CGPoint(x: 1, y: 1)
        pol.layer.addSublayer(gradientColor)

任何使渐变适应我视图的真实形状的解决方案?

gradientColor 图层的 mask 属性 设置为 CAShapeLayer() 并用黑色填充

 let mask = CAShapeLayer()
 mask.frame = // to whatever size it should be
 mask.path = yourShapeBezierHERE.cgPath
 mask.fillColor = UIColor.black.cgColor
 gradientColor.mask = mask