CALayer:我如何调用绘图功能?

时间:2018-01-18 17:43:35

标签: swift core-graphics draw calayer swift4

我已经将CALayer子类化为创建径向渐变(我从this code here开始)。问题是我需要更改渐变的颜色,这是绘制函数中的颜色。我希望每次更改colors时都能重新绘制图层。我无法直接致电draw(in:),因为我不知道要使用CGContext。有什么想法吗?

import Foundation
import UIKit

class CARadialGradientLayer: CALayer {

    required override init() {
        super.init()
        needsDisplayOnBoundsChange = true
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    required override init(layer: Any) {
        super.init(layer: layer)
    }

    public var colors = [UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5).cgColor, UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.00).cgColor] {
        didSet {


            /* Redraw the layer to update colors */


        }
    }

    override func draw(in ctx: CGContext) {
        ctx.saveGState()

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        var locations = [CGFloat]()

        for i in 0...colors.endIndex {
            locations.append(CGFloat(i) / CGFloat(colors.count))
        }

        let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: locations)
        let center = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)
        let radius = min(bounds.width / 2.0, bounds.height / 2.0)
        ctx.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: radius, options: CGGradientDrawingOptions(rawValue: 0))
    }
}

1 个答案:

答案 0 :(得分:3)

didSet中,拨打setNeedsDisplay()

当绘图发生时,这不取决于你。系统处理。但是你需要在需要绘图时告诉系统。