我在下面使用 Swift 2 代码在用户触摸屏幕并在屏幕上移动手指时绘制曲线。当用户移动他们的手指以在屏幕上给出一条连续的曲线时,曲线的新部分被添加。 (上图)
但是,我希望更改下面的代码,以便在添加该行的每个新部分并将其绘制到屏幕时,删除之前的部分和更早的部分,以便在屏幕上看到的都是新部分和没有其他的。 (下图)
为了实现这一点,下面的代码部分需要修改什么?
// Swift 2 code below tested using Xcode 7.0.1.
class drawLines: UIView {
let path=UIBezierPath()
var previousPoint:CGPoint = CGPoint.zero
var strokeColor:UIColor?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func drawRect(rect: CGRect) {
strokeColor = UIColor.blackColor()
strokeColor?.setStroke()
path.lineWidth = 10
path.stroke()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch: AnyObject? = touches.first
let currentPoint = touch!.locationInView(self)
path.moveToPoint(currentPoint)
previousPoint=currentPoint
self.setNeedsDisplay()
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch: AnyObject? = touches.first
let currentPoint = touch!.locationInView(self)
let midPoint = self.midPoint(previousPoint, p1: currentPoint)
path.addQuadCurveToPoint(midPoint,controlPoint: previousPoint)
previousPoint=currentPoint
self.setNeedsDisplay()
path.moveToPoint(midPoint)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.setNeedsDisplay()
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
self.touchesEnded(touches!, withEvent: event)
}
func midPoint(p0:CGPoint,p1:CGPoint)->CGPoint
{
let x=(p0.x+p1.x)/2
let y=(p0.y+p1.y)/2
return CGPoint(x: x, y: y)
}
}
最佳答案
据我所知,没有办法从 UIBezierPath
中删除点。您正在寻找的解决方案是将点存储在一个数组中,您可以自由修改,然后从该点数组创建您的路径。
更新
重新阅读您的帖子和您发表的评论时,我有点困惑。话虽如此,我已尝试让下面的示例包含您需要的所有元素——如果我没有 100% 理解您的意思,您可能需要重新安排它们。
此代码从触摸开始的点开始不断向数组添加点,包括在触摸开始时。我为最大点数添加了一个上限,以便在需要时删除多余的线点。当用户松开他们的手指时,我已经把所有的点都说清楚了。
注意:我尽量使代码尽可能简单,以使其清晰明了。一旦找到符合您需要的添加/删除点的正确组合,您可能应该考虑对其进行优化。特别是,这假定了一种朴素的绘图方法,其中所有绘图同时发生(与增量相比),这种方法效率不高。去除多余点的方法也可以在理解后进行优化。
import UIKit
class ViewController: UIViewController {
var points = [CGPoint]()
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
addTouch(touches.first)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
addTouch(touches.first)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
points.removeAll()
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
points.removeAll()
}
func addTouch(touch: UITouch?) {
guard let touch = touch else { return }
let currentPoint = touch.locationInView(self.view)
points.append(currentPoint)
// if you want a limit on your line length, you need these lines
// 20 is an arbitrary number
while (points.count > 20) {
points.removeFirst()
}
}
}
剩下的就是将其添加到当前的线条图代码中,您应该可以开始了。
Apple 在 WWDC 上就图形性能做了很多精彩的演讲。 This one in particular might be helpful.
关于ios - 在 Swift 中绘制新部分时删除旧的曲线部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34240041/