试过这段代码没有成功。
let gradient = CAGradientLayer()
gradient.frame = outerPath.bounds
gradient.colors = [UIColor.red.cgColor, UIColor.yellow.cgColor]
// mask
let shapeMask = CAShapeLayer()
shapeMask.path = outerPath.cgPath
self.insertSublayer(gradient, at: 0)
最佳答案
让 CAShapeLayer 做一个虚线 mask 。
class
TheView: UIView {
required init?( coder aDecoder: NSCoder ) {
super.init( coder: aDecoder )
let outerPath = UIBezierPath( ovalIn: bounds.insetBy( dx: 20, dy: 20 ) )
let gradient = CAGradientLayer()
gradient.frame = bounds
gradient.colors = [ UIColor.red.cgColor, UIColor.yellow.cgColor ]
let shapeMask = CAShapeLayer()
shapeMask.path = outerPath.cgPath
shapeMask.lineWidth = 8
shapeMask.lineDashPhase = 0
shapeMask.lineDashPattern = [ 6, 2 ]
shapeMask.lineCap = .butt
shapeMask.lineJoin = .bevel
shapeMask.strokeColor = UIColor.black.cgColor // Any color
shapeMask.fillColor = nil
gradient.mask = shapeMask
layer.addSublayer( gradient )
}
}
关于ios - 将渐变应用于虚线 UIBezierPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51449611/