画线时触摸结束时线不一致

Posted

技术标签:

【中文标题】画线时触摸结束时线不一致【英文标题】:line disagreeing when touch end when drawing line 【发布时间】:2020-12-02 05:49:49 【问题描述】:

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

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()
    

【问题讨论】:

【参考方案1】:

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

用下面的代码替换你的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()

【讨论】:

以上是关于画线时触摸结束时线不一致的主要内容,如果未能解决你的问题,请参考以下文章

在用户想要画线时获取 CGPoint 数组

当我慢慢画线时,图中的虚线不起作用

如何在 C# windows 窗体中绘制可缩放图像

为啥我在 UIView 上画线时需要背景颜色?

使用 Sprite Kit 画线时播放声音

触摸移动触发时css过渡不一致