Reputation: 3
I'm trying to change the line width of my drawing app using a slider but every time I change the slider and redraw a line, all lines on the screen change to the currently selected line width. I must be doing something wrong.
var layers:[Array<CGPoint>] = []
var layerIndex = 0
var sliderValue: CGFloat = 3.0
var strokeInfo:[[String:Any]] = []
//change the slider
func slider(value: CGFloat) {
sliderValue = value
print("Slider value is \(sliderValue)")
}
//on new touch, start a new array (layer) of points
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
var points:[CGPoint] = []
layers.append(points)
var info = Dictionary<String,Any>()
info["line"] = sliderValue
strokeInfo.insert(info, at: layerIndex)
let pt = (touches.first!).location(in: self)
points.append(pt)
}
//add each point to the correct array as the finger moves
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let pt = (touches.first!).location(in: self)
layers[layerIndex].append(pt)
self.setNeedsDisplay()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
print("layer \(layerIndex) now has \(layers[layerIndex].count)")
layerIndex += 1
}
override func draw(_ rect: CGRect) {
//get pointer to view
let context = UIGraphicsGetCurrentContext()
context?.clear(rect)
for (index, element) in strokeInfo.enumerated() {
if index == layerIndex {
context?.setLineWidth(element["line"] as! CGFloat)
}
}
//loop through the layers if any
for points in layers {
UIColor.cyan.set()
//loop through each layer's point values
if points.count - 1 > 0 {
for i in 0 ..< points.count-1 {
let pt1 = points[i] as CGPoint
let pt2 = points[i + 1] as CGPoint
context?.setLineCap(.round)
context?.move(to: pt1)
context?.addLine(to: pt2)
context?.strokePath()
}
}
}
}
Upvotes: 0
Views: 552
Reputation: 131418
You're changing the line width and line cap of the context. The settings of the graphics context affect the entire path associated with the context.
If you want to draw different paths, I suggest you use multiple UIBezierPath objects, each with it's own width, color, and line cap settings. You can draw your bezier paths in your drawRect method.
Alternately you could use multiple CAShapeLayers, each with different path drawing settings and stack them on top of each other to get the composite image you want.
Upvotes: 1