0

我的快速代码目标是在图像视图上画线。现在,当您从图像视图中拿起手时,绘图就会消失。当你的手被按下时,它就在你的手或点被释放时工作,没有任何东西被保存。我不知道我的代码中缺少什么来解决这个问题,它可能只是一行。

import UIKit
class ViewController: UIViewController {
    
    var statPoint = CGPoint.zero
    var swipe = false
    var pic = UIImageView()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        pic.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(pic)
        pic.backgroundColor = .brown
        view.backgroundColor = .cyan
        pic.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {
            return}
        
        swipe = false
        statPoint = touch.location(in: view)
    }
    
    func drawLine(from fromPoint: CGPoint, to toPoint : CGPoint)  {
        UIGraphicsBeginImageContext( view.frame.size)
        
        guard let context = UIGraphicsGetCurrentContext() else {
            return
        }
        
        pic.image?.draw(in: view.bounds)
        context.move(to: fromPoint)
        context.addLine(to: toPoint)
        context.setLineCap(.round)
        context.setLineWidth(5)
        context.setBlendMode(.normal)
        context.setStrokeColor(UIColor.black.cgColor)
        context.strokePath()
        pic.image = UIGraphicsGetImageFromCurrentImageContext()
        pic.alpha = 1
        
        UIGraphicsEndImageContext()
        
        
        
    }
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {
            return
            
        }
        swipe = true
        let currentPoint = touch.location(in: view)
        drawLine(from: statPoint, to: currentPoint)
        statPoint = currentPoint
    }
    
    
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if !swipe {
            drawLine(from: statPoint, to: statPoint)
        }
        
        UIGraphicsBeginImageContext(pic.frame.size)
        pic.image?.draw(in: view.bounds, blendMode: .normal, alpha: 1)
        pic.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    }
}
4

1 回答 1

0

我已经检查了你的代码。我认为问题在于您在 touchEnded 中使用的框架。

用下面的代码替换你的touchedEnded

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
   if !swipe {
       drawLine(from: statPoint, to: statPoint)
   }
       
   UIGraphicsBeginImageContext(view.frame.size)
   pic.image?.draw(in: view.bounds, blendMode: .normal, alpha: 1)
   pic.image = UIGraphicsGetImageFromCurrentImageContext()
   UIGraphicsEndImageContext()
}
于 2020-12-02T07:27:21.557 回答