利用 CAGradientLayer & mask 讓 CAShapeLayer 繪製的形狀變漸層
Published in
4 min readAug 8, 2020
利用 CAShapeLayer 我們能夠繪製各種形狀,可以填滿顏色,也可以只繪製線條。但是 CAShapeLayer 繪製的形狀要如何才能漸層呢 ?
我們可以用 CAGradientLayer 畫出長方形的漸層,然後將它的 mask 設為 CAShapeLayer 的資料,如此即可讓漸層的形狀變成 CAShapeLayer 的形狀。
接著讓我們看看以下兩個漸層三角形的例子吧。
實心漸層三角形
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let path = UIBezierPath()
path.move(to: CGPoint(x: 30, y: 50))
path.addLine(to: CGPoint(x: 100, y: 20))
path.addLine(to: CGPoint(x: 100, y: 100))
path.close()
let triangleLayer = CAShapeLayer()
triangleLayer.path = path.cgPath
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [CGColor(red: 1, green: 0, blue: 0, alpha: 1), CGColor(red: 1, green: 1, blue: 1, alpha: 1)]
gradientLayer.frame = CGRect(x: 30, y: 30, width: 100, height: 100)
view.layer.addSublayer(gradientLayer)
gradientLayer.mask = triangleLayer
}
}
三角形線條
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let path = UIBezierPath()
path.move(to: CGPoint(x: 30, y: 50))
path.addLine(to: CGPoint(x: 100, y: 20))
path.addLine(to: CGPoint(x: 100, y: 100))
path.close()
let triangleLayer = CAShapeLayer()
triangleLayer.path = path.cgPath
triangleLayer.fillColor = UIColor.clear.cgColor
triangleLayer.lineWidth = 3
triangleLayer.strokeColor = CGColor(srgbRed: 1, green: 0, blue: 0, alpha: 1)
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [CGColor(red: 1, green: 0, blue: 0, alpha: 1), CGColor(red: 1, green: 1, blue: 1, alpha: 1)]
gradientLayer.frame = CGRect(x: 30, y: 30, width: 100, height: 100)
view.layer.addSublayer(gradientLayer)
gradientLayer.mask = triangleLayer
}
}