【问题标题】:CALayer: How do I call the draw function?CALayer:如何调用绘图函数?
【发布时间】:2018-01-18 17:43:34
【问题描述】:

我对 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))
    }
}

【问题讨论】:

    标签: swift core-graphics draw calayer swift4


    【解决方案1】:

    didSet,拨打setNeedsDisplay()

    绘制发生时不取决于您。系统会处理。但何时需要绘图由您来告诉系统。

    【讨论】:

    • 谢谢。我试过了,它确实调用了绘图函数,但由于某种原因它没有改变渐变
    猜你喜欢
    • 2012-02-17
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多