swift - CALayer:如何调用绘制函数?

标签 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))
    }
}

最佳答案

didSet中,调用setNeedsDisplay()

绘制发生时不由您决定。系统处理那个。但是您可以在需要绘图时告诉系统。

关于swift - CALayer:如何调用绘制函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48327326/

相关文章:

ios - 从 firebase 读取数据并填充 TableViewCell

ios - 如何圆 UIBezierPath 线边缘?

ios - 如何在 Swift 中保存 CoreGraphics 绘图

ios - UIBezierPath 和 NSBezierPath 在绘制圆弧时产生不同的结果

xna - 沿对角线移动 Sprite

iphone - 使用 iPhone map 套件在引脚之间绘制线条

c - 如何为每个数字输入添加一个输出?

swift - 在 UITableviewcells 中一起滚动 UIScrollviews

ios - UIAlertView 仅显示一次

ios - 带有 UIAppearance 的自定义类上的圆形按钮