绘制视图:绘图与手指或光标的位置不同

问题描述 投票:0回答:1

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

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

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()}
swift
1个回答
0
投票

尝试改变你的imageView临时

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

和:

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

祝好运

© www.soinside.com 2019 - 2024. All rights reserved.