/// 聚光灯效果的遮罩
class SpotlightFilterMaskLayer : CALayer {
/// 坡度的宽度
var gradientWidth: CGFloat = 40.0
/// 直径
var diameter: CGFloat = 0 {
didSet {
setNeedsDisplay()
}
}
override func draw(in ctx: CGContext) {
let origin: CGPoint = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
let clearRegionRadius: CGFloat = self.diameter * 0.5
let blurRegionRadius: CGFloat = clearRegionRadius + gradientWidth
// 创建颜色空间
let baseColorSpace = CGColorSpaceCreateDeviceRGB();
let colours : [CGFloat] = [0.0, 0.0, 0.0, 1,
0.0, 0.0, 0.0, 0.2]
let colourLocations : [CGFloat] = [0, 1]
// 创建渐变对象
// - colorSpace: 颜色空间
// - colorComponents: 颜色分量的强度值数组
// - locations: 渐变系数数组
// - count: 设置的渐变系数数组的元素个数
guard let gradient = CGGradient(colorSpace: baseColorSpace,
colorComponents: colours,
locations: colourLocations,
count: 2) else {
return
}
// 绘制渐变
// - gradient: 渐变对象
// - startCenter: 起点
// - startRadius: 径向半径
// - endCenter: 终点
// - endRadius: 径向半径
// - options: 渐变模式
// - .drawsBeforeStartLocation 表示向里发散
// - .drawsAfterEndLocation 表示向外发散
ctx.drawRadialGradient(gradient,
startCenter: origin,
startRadius: clearRegionRadius,
endCenter: origin,
endRadius: blurRegionRadius,
options: .drawsBeforeStartLocation);
ctx.drawPath(using: .fill)
}
}
评论