【问题标题】:change color from CGPoint line in a subclass of uiview从 uiview 的子类中的 CGPoint 线更改颜色
【发布时间】:2019-10-27 19:45:15
【问题描述】:

当调用 View Controller 类中的 func dizzy 时,我的代码试图将线条的颜色从红色更改为蓝色。问题是我不知道如何从类视图控制器中做到这一点。我可以在 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】:

    将名为strokeColor 的属性添加到您的Canvas

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

    draw(rect:) 中使用strokeColor

    context.setStrokeColor(strokeColor.cgColor)
    

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

    class ViewController: UIViewController {
        var canvas = Canvas()
    
        @objc func dizzy() {
            canvas.strokeColor = .blue
        }
    }
    

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多