UIView漸變色 , UIView及其子類都可以使用,比如UIButton、UILabel等。
代碼如下:
//
// UIView+Gradient.swift
// NEOKit
//
// Created by 秦偉 on 2017/10/19.
//
// UIView 漸變色 , UIView及其子類都可以使用,比如UIButton、UILabel等。
//
// Usage:
// myButton.gradientColor(CGPoint(x: 0, y: 0.5), CGPoint(x: 1, y: 0.5), [UIColor(hex: "#FF2619").cgColor, UIColor(hex: "#FF8030").cgColor])
import UIKit
public extension UIView {
// MARK: 添加漸變色圖層
public func gradientColor(_ startPoint: CGPoint, _ endPoint: CGPoint, _ colors: [Any]) {
guard startPoint.x >= 0, startPoint.x <= 1, startPoint.y >= 0, startPoint.y <= 1, endPoint.x >= 0, endPoint.x <= 1, endPoint.y >= 0, endPoint.y <= 1 else {
return
}
// 外界如果改變了self的大小,需要先刷新
layoutIfNeeded()
var gradientLayer: CAGradientLayer!
removeGradientLayer()
gradientLayer = CAGradientLayer()
gradientLayer.frame = self.layer.bounds
gradientLayer.startPoint = startPoint
gradientLayer.endPoint = endPoint
gradientLayer.colors = colors
gradientLayer.cornerRadius = self.layer.cornerRadius
gradientLayer.masksToBounds = true
// 漸變圖層插入到最底層,避免在uibutton上遮蓋文字圖片
self.layer.insertSublayer(gradientLayer, at: 0)
self.backgroundColor = UIColor.clear
// self如果是UILabel,masksToBounds設(shè)為true會導致文字消失
self.layer.masksToBounds = false
}
// MARK: 移除漸變圖層
// (當希望只使用backgroundColor的顏色時,需要先移除之前加過的漸變圖層)
public func removeGradientLayer() {
if let sl = self.layer.sublayers {
for layer in sl {
if layer.isKind(of: CAGradientLayer.self) {
layer.removeFromSuperlayer()
}
}
}
}
}