CAGradientLayer没有得到形状

问题描述 投票:0回答:1

我正在创建一个马蹄形的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)
ios swift gradient shape layer
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.