我的代码正在尝试使用滑动值来更改线条的宽度。现在,它不起作用。我只希望不要在更改值之前绘制线条,而仅在更改值之后才使用新线条。请查看Canvas类中的增值税号。 Struct ColoredLine控制线条的颜色。
struct ColoredLine {
var color = UIColor.black
var points = [CGPoint]()
}
class ViewController: UIViewController {
@objc func hhh() {
canvas.number = Int(justinBiber.value)
}
var justinBiber = UISlider()
}
class Canvas: UIView {
var strokeColor = UIColor.green
var number = 5
func undo() {
_ = lines.popLast()
setNeedsDisplay()
}
func clear() {
lines.removeAll()
setNeedsDisplay()
}
var lines = [ColoredLine]()
override func draw(_ rect: CGRect) {
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext() else { return }
context.setLineWidth(number)
context.setLineCap(.butt)
lines.forEach { (line) in
for (i, p) in line.points.enumerated() {
if i == 0 {
context.move(to: p)
} else {
context.addLine(to: p)
}
}
context.setStrokeColor(line.color.cgColor)
context.strokePath()
context.beginPath()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
var coloredLine = ColoredLine()
coloredLine.color = strokeColor
lines.append(coloredLine)
}
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.points.append(point)
lines.append(lastLine)
setNeedsDisplay()
}
}
线宽只是您的线的另一个属性。将该属性添加到ColoredLine
struct
:
struct ColoredLine {
var color = UIColor.black
var width = 5
var points = [CGPoint]()
}
将strokeWidth
属性添加到Canvas
类,并在滑块值更改时对其进行更新:
class Canvas : UIView {
var strokeWidth = 5
....
}
在touchesBegan()
中,将strokeWidth
的当前值添加到coloredLine
实例:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
var coloredLine = ColoredLine()
coloredLine.color = strokeColor
coloredLine.width = strokeWidth
lines.append(coloredLine)
}
然后在draw(rect:)
中画线之前设置context
的strokeWidth
:
lines.forEach { (line) in
for (i, p) in line.points.enumerated() {
if i == 0 {
context.move(to: p)
} else {
context.addLine(to: p)
}
}
context.setStrokeColor(line.color.cgColor)
context.setLineWidth(line.width)
context.strokePath()
context.beginPath()
}