用核心图形画线

Drawing lines with core graphics

我想在核心图形中绘制不止一条直线。或保存该行并开始一个新行。我为触摸位置使用了两个变量,并在 touch 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()
    }
}

尝试像这样使用 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)
   }

希望对您有所帮助!

你必须有一个代表线条的模型对象,例如:LineAnnotationLineAnnotation 将保存起点和终点、颜色和许多其他有关线条的详细信息。将每个 LineAnnotation(line) 保存在一个数组中。遍历这个数组,一条一条地画线。在您的情况下,正在使用最新数据进行绘图。当您调用 setNeedsDisplay()

时,先前绘制的点将被刷新

根据 apples 文档 (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()
}

}