我尝试使用滑块更改绘图应用的线宽,但每次更改滑块并重新绘制线条时,屏幕上的所有线条都会更改为当前所选行宽。我一定是做错了。
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()
}
}
}
}
答案 0 :(得分:1)
您正在更改上下文的线宽和线上限。图形上下文的设置会影响与上下文关联的整个路径。
如果你想绘制不同的路径,我建议你使用多个UIBezierPath对象,每个对象都有自己的宽度,颜色和线帽设置。您可以在drawRect方法中绘制贝塞尔曲线路径。
或者你可以使用多个CAShapeLayers,每个都有不同的路径绘图设置,并将它们叠加在一起,以获得你想要的合成图像。