快速更改图层颜色

时间:2018-09-10 06:32:14

标签: ios swift

当前在我的应用中,当用户点击屏幕时,如果用户多次触摸屏幕,则在用户触摸的任何地方都会出现一个红点。我想添加一个功能以允许用户更改颜色。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first as UITouch?{
        let location = (touch as! UITouch).location(in: self.imageView)
        let layer = CAShapeLayer()

        layer.path = UIBezierPath(roundedRect: CGRect(x: location.x, y: location.y, width: 2, height: 2), cornerRadius: 50).cgPath
        layer.fillColor = UIColor.red.cgColor

        imageView.layer.addSublayer(layer)
    }
}

当我尝试以下方法时,我可以更改颜色,但是由于某种原因,无论我在屏幕上点击多少次,都只会出现一个点。我的猜测是,每次我在屏幕上点击都会创建一个新层,它将替换旧层。无论如何,我可以允许用户更改图层的颜色,同时保留图层上已经存在的所有点吗?

class ViewController: UIViewController,UIScrollViewDelegate      {
    let layer = CAShapeLayer()
    override func viewDidLoad() {
        super.viewDidLoad()
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first as UITouch?{
            let location = (touch as! UITouch).location(in: self.imageView)


            layer.path = UIBezierPath(roundedRect: CGRect(x: location.x, y: location.y, width: 2, height: 2), cornerRadius: 50).cgPath
            layer.fillColor = UIColor.red.cgColor

            imageView.layer.addSublayer(layer)
        }
    }
    @IBAction func changecolorBtn(_ sender: Any) {
        layer.fillColor = UIColor.green.cgColor
    }
}

1 个答案:

答案 0 :(得分:0)

因为您只使用了一层

let layer = CAShapeLayer()

以及每次设置

layer.path = UIBezierPath(roundedRect: CGRect(x: location.x, y: location.y, width: 2, height: 2), cornerRadius: 50).cgPath

它将删除旧路径,而新路径只有​​一点。

这就是为什么

  

当我尝试以下方法时,我可以更改颜色,但是由于某种原因,无论我在屏幕上点击多少次,都只会出现一个点。

您可以通过合并所有dot path来简单地解决问题。像这样

// add the combine path as your global variable
let layer = CAShapeLayer()
let combinePath = CGMutablePath()

并更改您的添加路径代码

layer.path = UIBezierPath(roundedRect: CGRect(x: location.x, y: location.y, width: 2, height: 2), cornerRadius: 50).cgPath

添加合并路径

let path = UIBezierPath(roundedRect: CGRect(x: location.x, y: location.y, width: 2, height: 2), cornerRadius: 50).cgPath
combinePath.addPath(path)
layer.path = combinePath