CAGradientLayer没有得到形状

时间:2017-12-21 13:07:23

标签: ios swift gradient shape layer

我正在创建一个马蹄形的CAGradientLayer。它似乎没有走这条路,只是画了一个带阴影的正方形。我错过了什么?

let gradientLayerContainer = CAShapeLayer()
        let gradient = CAGradientLayer()
        let segmentGradientPath = UIBezierPath.horseshoe(
            center: centerPoint,
            innerRadius: (bounds.width / 2) - config.ringWidth,
            outerRadius: bounds.width / 2,
            startAngle: segmentTapped.startAngle,
            endAngle: segmentTapped.endAngle)
        gradientLayerContainer.fillColor = UIColor.clear.cgColor
        gradientLayerContainer.path = segmentGradientPath.cgPath

        let end = centerPoint
        let start = centerPoint.shifted(outerRadius, with: segmentTapped.centerAngle)
        gradient.startPoint = CGPoint(x: start.x / bounds.width, y: start.y / bounds.height)
        gradient.endPoint = CGPoint(x: end.x / bounds.width, y: end.y / bounds.height)
        gradient.colors = [UIColor.white.withAlphaComponent(0.0).cgColor, UIColor.white.cgColor]
        gradient.frame = segmentGradientPath.bounds
        gradient.mask = gradientLayerContainer
        gradient.locations = [0, 1]


        horseshoeLayer.addSublayer(gradientLayerContainer)
        gradientLayerContainer.insertSublayer(gradient, at: 0)

1 个答案:

答案 0 :(得分:1)

蒙版属于渐变图层。渐变图层不属于遮罩。此外,在您希望渐变显示的任何地方,面具颜色都需要是不透明的(您使用的是相反的透明)。

以下是正确层次结构的Playground示例:

import PlaygroundSupport
import UIKit

let rect = CGRect(x: 0, y: 0, width: 300, height: 300)
let gradient = CAGradientLayer()
let maskLayer = CAShapeLayer()
let maskPath = UIBezierPath(ovalIn: rect)
maskLayer.fillColor = UIColor.black.cgColor
maskLayer.path = maskPath.cgPath
gradient.colors = [UIColor.blue.cgColor, UIColor.red.cgColor]
gradient.mask = maskLayer
gradient.locations = [0, 1]

let view = UIView(frame: rect)
view.layer.addSublayer(gradient)
gradient.frame = view.bounds
PlaygroundPage.current.liveView = view