我想在核心图形中绘制多条直线。或保存该行并开始一个新行。我使用两个变量进行触摸位置并为触摸位置分配触摸Began,Moved,Ended然后我使用了这个:
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(UIColor(red: 0, green: 0, blue: 0, alpha: 1.0).cgColor)
context?.setLineWidth(5.0)
context?.move(to: CGPoint(x: firstTouchLocation.x, y: firstTouchLocation.y))
context?.addLine(to: CGPoint(x: lastTouchLocation.x, y: lastTouchLocation.y))
context?.strokePath()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
firstTouchLocation = touch.location(in: self)
lastTouchLocation = firstTouchLocation
setNeedsDisplay()
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
lastTouchLocation = touch.location(in: self)
setNeedsDisplay()
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
lastTouchLocation = touch.location(in: self)
setNeedsDisplay()
}
}
答案 0 :(得分:2)
尝试使用CAShapeLayer绘制线条,如下所示:
func addLine(fromPoint start: CGPoint, toPoint end:CGPoint) {
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.move(to: start)
linePath.addLine(to: end)
line.path = linePath.cgPath
line.strokeColor = UIColor.red.cgColor
line.lineWidth = 1
line.lineJoin = kCALineJoinRound
self.view.layer.addSublayer(line)
}
希望这有帮助!
答案 1 :(得分:0)
你必须有一个代表一行的模型对象,例如ex: LineAnnotation 。 LineAnnotation 将包含该行的起点和终点,颜色以及许多其他详细信息。在数组中保存每个 LineAnnotation (行)。遍历此数组并逐行绘制线条。在您的情况下使用最新数据绘图。当您调用setNeedsDisplay()
时,将刷新以前绘制的点答案 2 :(得分:0)
根据苹果文档(https://developer.apple.com/documentation/uikit/uiview/1622437-setneedsdisplay) setNeedsDisplay 方法重绘您的视图,因此您只剩下最新行的全新视图。
要解决您的问题,只需在方法中提取代码,并在触摸时调用该方法。
override func draw(_ rect: CGRect) {
drawLine()
}
func drawLine()
{
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(UIColor(red: 0, green: 0, blue: 0, alpha: 1.0).cgColor)
context?.setLineWidth(5.0)
context?.move(to: CGPoint(x: firstTouchLocation.x, y: firstTouchLocation.y))
context?.addLine(to: CGPoint(x: lastTouchLocation.x, y: lastTouchLocation.y))
context?.strokePath()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
firstTouchLocation = touch.location(in: self)
lastTouchLocation = firstTouchLocation
drawLine()
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
lastTouchLocation = touch.location(in: self)
drawLine()
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
lastTouchLocation = touch.location(in: self)
drawLine()
}
}