绘图视图:绘图与手指或光标不在同一位置

时间:2018-09-05 21:14:52

标签: swift

我创建了一个可以绘制的视图,但是当我绘制时,该线在光标或手指的下方创建。

红线是我的手指或光标的移动,黑线是绘制的内容

enter image description here

   class DrawViewController: UIViewController {

        @IBOutlet weak var imageView: UIImageView!
        var lastPoint = CGPoint.zero
        var swiped = false

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

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

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

            context?.move(to: CGPoint(x: fromPoint.x, y: fromPoint.y))
            context?.addLine(to: CGPoint(x: toPoint.x, y: toPoint.y))

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

            context?.strokePath()

            imageView.image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
        }

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

        override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?){ if !swiped { drawLines(fromPoint: lastPoint, toPoint: lastPoint) } }

        override func viewDidLoad() {super.viewDidLoad()}
        override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()}

1 个答案:

答案 0 :(得分:0)

尝试将imageView的温度更改为

imageView.image?.draw(in: view.bounds)

和:

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

祝你好运