从uiview的子类中的CGPoint线更改颜色

问题描述 投票:0回答:1

我的代码试图在类View Controller中调用func头晕时将线的颜色从红色更改为蓝色。问题是我不知道如何从类视图控制器做到这一点。我可以在Canvas类中做到这一点,但是我需要通过func晕眩来控制它,因为它充当viewController类中的按钮。我不在乎是否必须在canvas func中创建一个func然后从viewController中调用它。

class ViewController: UIViewController {
    var canvas = Canvas()
@objc func dizzy() {

}}



    class Canvas: UIView {

// public function
func undo() {
    _ = lines.popLast()
    setNeedsDisplay()
}

func clear() {
    lines.removeAll()
    setNeedsDisplay()
}




var lines = [[CGPoint]]()

override func draw(_ rect: CGRect) {
    super.draw(rect)

    guard let context = UIGraphicsGetCurrentContext() else { return }

    context.setStrokeColor(UIColor.red.cgColor)
    context.setLineWidth(5)
    context.setLineCap(.butt)

    lines.forEach { (line) in
        for (i, p) in line.enumerated() {
            if i == 0 {
                context.move(to: p)
            } else {
                context.addLine(to: p)
            }
        }
    }

    context.strokePath()

}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    lines.append([CGPoint]())
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let point = touches.first?.location(in: self) else { return }
    guard var lastLine = lines.popLast() else { return }
    lastLine.append(point)
    lines.append(lastLine)
    setNeedsDisplay()
}

}
swift uiview subclass cgpoint uigraphicscontext
1个回答
0
投票

strokeColor中添加一个名为Canvas的属性:

class Canvas : UIView {
    var strokeColor = UIColor.red {
        didSet {
            self.setNeedsDisplay()
        }
    }

    ... 
}

strokeColor中使用draw(rect:)

context.setStrokeColor(strokeColor.cgColor)

然后在dizzy()中将画布的strokeColor设置为.blue

class ViewController: UIViewController {
    var canvas = Canvas()

    @objc func dizzy() {
        canvas.strokeColor = .blue
    }
}

每次设置strokeColorCanvas时,都会通过在其self.setNeedsDisplay()属性观察器中调用didSet来触发重绘。对draw(rect:)的新调用将使用新颜色重绘视图。

© www.soinside.com 2019 - 2024. All rights reserved.