gpt4 book ai didi

swift - 更改 uiview 子类中 CGPoint 线的颜色

转载 作者:行者123 更新时间:2023-11-30 10:33:30 25 4
gpt4 key购买 nike

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

}

最佳答案

将名为 linesColor 的属性添加到 Canvas 中:

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

...
}

draw(rect:)中使用linesColor:

context.setStrokeColor(strokeColor.cgColor)

然后在dizzy()中将 Canvas 的linesColor设置为.blue:

class ViewController: UIViewController {
var canvas = Canvas()

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

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

关于swift - 更改 uiview 子类中 CGPoint 线的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58582758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com