gpt4 book ai didi

ios - 快速改变图层颜色

转载 作者:行者123 更新时间:2023-11-30 11:10:23 26 4
gpt4 key购买 nike

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

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

最佳答案

因为你只用了一层

let layer = CAShapeLayer()

无论何时设置

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

它将删除旧路径,并且您的新路径只有​​一个点。

这就是为什么

When I tried the following method I am able to change the colour but for some reason no matter how many times I've tap on the screen there will only be one dot.

您可以通过组合所有点路径来简单地解决您的问题。像这样

// 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

关于ios - 快速改变图层颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52252242/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com