如何将Gradient应用于iOS Swift App的后台视图我正在尝试应用渐变作为视图的背景颜色(故事板的主视图)。代码运行,但没有任何变化。我正在使用xCode Beta 2和Swift。这是代码:class Colors {
let colorTop = UIColor(red: 192.0/255.0, green: 38.0/255.0, blue: 42.0/255.0, alpha: 1.0)
let colorBottom = UIColor(red: 35.0/255.0, green: 2.0/255.0, blue: 2.0/255.0, alpha: 1.0)
let gl: CAGradientLayer
init() {
gl = CAGradientLayer()
gl.colors = [ colorTop, colorBottom]
gl.locations = [ 0.0, 1.0]
}}然后在视图控制器中: let colors = Colors()
func refresh() {
view.backgroundColor = UIColor.clearColor()
var backgroundLayer = colors.gl
backgroundLayer.frame = view.frame
view.layer.insertSublayer(backgroundLayer, atIndex: 0)
}
}
}
3 回答
LEATH
TA贡献1936条经验 获得超6个赞
Xcode 8.2•Swift 3.0.2
您可以设计自己的渐变视图,如下所示:
@IBDesignableclass GradientView: UIView { @IBInspectable var startColor: UIColor = .black { didSet { updateColors() }} @IBInspectable var endColor: UIColor = .white { didSet { updateColors() }} @IBInspectable var startLocation: Double = 0.05 { didSet { updateLocations() }} @IBInspectable var endLocation: Double = 0.95 { didSet { updateLocations() }} @IBInspectable var horizontalMode: Bool = false { didSet { updatePoints() }} @IBInspectable var diagonalMode: Bool = false { didSet { updatePoints() }} override public class var layerClass: AnyClass { return CAGradientLayer.self } var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer } func updatePoints() { if horizontalMode { gradientLayer.startPoint = diagonalMode ? CGPoint(x: 1, y: 0) : CGPoint(x: 0, y: 0.5) gradientLayer.endPoint = diagonalMode ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0.5) } else { gradientLayer.startPoint = diagonalMode ? CGPoint(x: 0, y: 0) : CGPoint(x: 0.5, y: 0) gradientLayer.endPoint = diagonalMode ? CGPoint(x: 1, y: 1) : CGPoint(x: 0.5, y: 1) } } func updateLocations() { gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber] } func updateColors() { gradientLayer.colors = [startColor.cgColor, endColor.cgColor] } override public func layoutSubviews() { super.layoutSubviews() updatePoints() updateLocations() updateColors() }}
慕的地10843
TA贡献1785条经验 获得超8个赞
如果您需要更改渐变的方向,则必须使用startPoint和endPoint。
let gradient: CAGradientLayer = CAGradientLayer()gradient.colors = [UIColor.blue.cgColor, UIColor.red.cgColor]gradient.locations = [0.0 , 1.0]gradient.startPoint = CGPoint(x: 0.0, y: 1.0)gradient.endPoint = CGPoint(x: 1.0, y: 1.0)gradient.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.view.frame.size.height)self.view.layer.insertSublayer(gradient, atIndex: 0)
- 3 回答
- 0 关注
- 572 浏览
添加回答
举报
0/150
提交
取消