将渐变颜色添加到自定义UIView

时间:2017-05-15 21:01:28

标签: swift uiview layer uibezierpath cagradientlayer

我实现了一个自定义的UIView类来实现一种空中飞人;以下代码我用来实现这个类:

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)

enter image description here

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

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)

enter image description here

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

1 个答案:

答案 0 :(得分:2)

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