Swift 5在UIView中绘制签名出现偏移问题求助
解决签名绘制轨迹与光标位置偏移的问题
你的问题根源在于触摸事件获取坐标时使用了错误的参考系!
在touchesMoved方法里,你用了location(in: nil),这个方法会返回触摸点相对于整个屏幕的坐标。但你的Canvas是一个子视图,绘制时使用的是自身的本地坐标系统,两者之间存在布局偏移(比如导航栏、安全区域的高度差),这就导致了绘制轨迹比实际触摸位置低。
修复步骤:
修正
touchesMoved中的坐标获取:
将获取触摸点的代码从:guard let point = touches.first?.location(in: nil) else { return }改为:
guard let point = touches.first?.location(in: self) else { return }同时修正
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
相关产品推荐
相关产品推荐

