Zeichnen Sie eine Linie in Echtzeit mit Swift 3.0

Ich versuche, auf eine UIImageView zu zeichnen. Mit Swift 1.2 konnte ich es zum Laufen bringen, aber ich musste es auf Swift 3.0 konvertieren und kann es einfach nicht zum Laufen bringen.

ie müssen nur genau das zeichnen, was Sie mit dem Finger auf dem Bildschirm zeichnen.

Der Code gibt keine Fehler aus, zeigt aber nichts an.

Variablen

var lastPoint = CGPoint.zero
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var brushWidth: CGFloat = 10.0
var opacity: CGFloat = 1.0
var swiped = false

Der Code

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = false
    if let touch = touches.first {
        lastPoint = touch.location(in: self.view)
    }
}

func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {


    imageView.image?.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
    UIGraphicsBeginImageContext(self.imageView.bounds.size);
    let context = UIGraphicsGetCurrentContext()

        context?.move(to: fromPoint)
        context?.addLine(to: toPoint)

        context?.setLineCap(CGLineCap.round)
        context?.setLineWidth(brushWidth)
        context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
        context?.setBlendMode(CGBlendMode.normal)

        imageView.image = UIGraphicsGetImageFromCurrentImageContext()
        imageView.alpha = opacity
        UIGraphicsEndImageContext()

}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = true
    if let touch = touches.first {
        let currentPoint = touch.location(in: view)
        drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint)

        lastPoint = currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if !swiped {
                    // draw a single point
        self.drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint)
    }

Antworten auf die Frage(2)

Ihre Antwort auf die Frage