将UIView包裹在SwiftUI周围,触摸和绘制坐标现在未对齐吗?

问题描述

我有一个Canvas视图,如下所示

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
    }
}

一切正常。我可以根据发生触摸的位置进行绘制,如下所示。

enter image description here

但是,如果我将其包裹在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
    }
}

我的触摸和绘画不匹配。绘制坐标低于触摸发生的位置,如下所示

enter image description here

在将它包裹在SwiftUI上时,我是否错过了任何东西,因为触摸和绘制坐标现在未对齐?

解决方法

您遇到的问题与SwiftUI无关,而是在您的代码中

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

您应该使用

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