You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 5在UIView中绘制签名出现偏移问题求助

解决签名绘制轨迹与光标位置偏移的问题

你的问题根源在于触摸事件获取坐标时使用了错误的参考系!

在touchesMoved方法里,你用了location(in: nil),这个方法会返回触摸点相对于整个屏幕的坐标。但你的Canvas是一个子视图,绘制时使用的是自身的本地坐标系统,两者之间存在布局偏移(比如导航栏、安全区域的高度差),这就导致了绘制轨迹比实际触摸位置低。

修复步骤:

  1. 修正touchesMoved中的坐标获取:
    将获取触摸点的代码从:

    guard let point = touches.first?.location(in: nil) else { return }
    

    改为:

    guard let point = touches.first?.location(in: self) else { return }
    
  2. 同时修正touchesBegan(可选但推荐):
    虽然当前touchesBegan只是创建空的Line,但如果后续需要记录起始点的话,也应该用自身坐标。补充代码确保起始点正确:

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let point = touches.first?.location(in: self) else { return }
        lines.append(Line(strokeWidth: strokeWidth, color: strokeColor, points: [point]))
    }
    

    这样可以避免绘制的第一条线起始点也出现偏移。

为什么这样能解决问题?

  • location(in: self)会返回触摸点相对于当前Canvas视图的本地坐标,和你在draw(_ rect:)方法中使用的绘制坐标系统完全匹配,这样触摸位置和绘制轨迹就能一一对应了。

内容的提问来源于stack exchange,提问作者Flo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:08:07