Swift 绘图应用程序 - 根据滑块更改线宽值

Swift drawing app - changing line width value based on a slider

我正在尝试使用滑块更改我的绘图应用程序的线宽,但每次我更改滑块并重新绘制一条线时,屏幕上的所有线都会变为当前选择的线宽。我一定是做错了什么。

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()
        }
        }
    }
}

您正在更改上下文的线宽和线帽。图形上下文的设置会影响与上下文关联的整个路径。

如果你想绘制不同的路径,我建议你使用多个 UIBezierPath 对象,每个对象都有自己的宽度、颜色和线帽设置。您可以在 drawRect 方法中绘制贝塞尔曲线路径。

或者,您可以使用多个 CAShapeLayer,每个具有不同的路径绘制设置,并将它们堆叠在一起以获得您想要的合成图像。