Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 我如何调用draw函数?_Swift_Core Graphics_Draw_Calayer_Swift4 - Fatal编程技术网

Swift 我如何调用draw函数?

Swift 我如何调用draw函数?,swift,core-graphics,draw,calayer,swift4,Swift,Core Graphics,Draw,Calayer,Swift4,我已经对CALayer进行了子类化,以创建我开始使用的径向渐变。问题是我需要改变渐变的颜色,它在draw函数中。我希望能够在每次更改颜色时重新绘制图层。我不能直接调用drawin:因为我不知道使用什么CGContext。有什么想法吗 import Foundation import UIKit class CARadialGradientLayer: CALayer { required override init() { super.init() n

我已经对CALayer进行了子类化,以创建我开始使用的径向渐变。问题是我需要改变渐变的颜色,它在draw函数中。我希望能够在每次更改颜色时重新绘制图层。我不能直接调用drawin:因为我不知道使用什么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

画画的时间不由你决定。系统会处理这个问题。但何时需要绘图取决于您告诉系统。

在didSet中,调用setNeedsDisplay


画画的时间不由你决定。系统会处理这个问题。但是,当需要绘图时,由您告诉系统。

谢谢。我试过了,它确实调用了draw函数,但由于某种原因,它没有改变GradientThank。我试过了,它确实调用了draw函数,但由于某种原因,它没有改变渐变