如何解决将UIView包裹在SwiftUI周围,触摸和绘制坐标现在未对齐吗?
class Canvas: UIView {
override func draw(_ rect: CGRect){
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext() else { return }
paths.forEach { path in
switch(path.type) {
case .move:
context.move(to: path.point)
break
case .line:
context.addLine(to: path.point)
break
}
}
context.setlinewidth(10)
context.setLineCap(.round)
context.strokePath()
}
var paths = [Path]()
override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?) {
guard let point = touches.first?.location(in: nil) else { return }
paths.append(Path(type: .move,point: point))
setNeedsdisplay()
}
override func touchesMoved(_ touches: Set<UITouch>,with event: UIEvent?) {
guard let point = touches.first?.location(in: nil) else { return }
paths.append(Path(type: .line,point: point))
setNeedsdisplay()
}
}
class Path {
let type: PathType
let point: CGPoint
init(type: PathType,point: CGPoint) {
self.type = type
self.point = point
}
enum PathType {
case move
case line
}
}
当我使用普通的ViewController加载它时,
class ViewController: UIViewController {
let canvas = Canvas()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(canvas)
canvas.backgroundColor = .white
canvas.frame = view.frame
}
}
一切正常。我可以根据发生触摸的位置进行绘制,如下所示。
但是,如果我将其包裹在SwiftUI框架中,如下所示
struct ContentView: View {
var body: some View {
CanvasSwiftUI()
}
}
struct CanvasSwiftUI : UIViewRepresentable {
func makeUIView(context: Context) -> UIView {
Canvas()
}
func updateUIView(_ uiView: UIView,context: Context) {
uiView.backgroundColor = .white
}
}
我的触摸和绘画不匹配。绘制坐标低于触摸发生的位置,如下所示
在将它包裹在SwiftUI上时,我是否错过了任何东西,因为触摸和绘制坐标现在未对齐?
解决方法
您遇到的问题与SwiftUI无关,而是在您的代码中
guard let point = touches.first?.location(in: nil) else { return }
您应该使用
guard let point = touches.first?.location(in: self) else { return }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。