0

请注意,我到处找了很多东西,但找不到解决方案。

使用Storyboard,我有一个ViewController,一个视图(UIView)和一个子视图(PKCanvasView),我想使用PencilKit在后者上绘制。

_

我的目标是:

  1. 仅在此PKCanvasView上绘制

  2. 实时获取我在PKCanvasView上绘制的坐标

我的结果

  1. 只有从这个视图开始,我才能PKCanvasView上绘图,而且我只能在这个PKCanvasView的框架内绘图。那挺好的。

  2. 如果我在UIView上开始手势,我只能设法获得触摸屏幕位置的坐标。但是,如果我先触摸PKCanvasView ,则不会。

我的问题

如何获取我在 PKCanvasView 上绘制位置的坐标?

——</p>

下面是我的代码

import UIKit
import PencilKit

class ViewController: UIViewController {

    @IBOutlet weak var labelText: UILabel! //Label object to display the coordinates

    @IBOutlet weak var canvasView: PKCanvasView! //Subview to draw on

    override func viewDidAppear(_ animated: Bool) {
        canvasView.tool = PKInkingTool(.pen, color: .black, width: 10)
    }

    // MARK: FUNCTIONS //
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        touches.forEach { (touch) in
            updateGagues(with: touch)
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        touches.forEach { (touch) in
            updateGagues(with: touch)
        }
    }

    private func updateGagues(with touch: UITouch) {
        let location = touch.preciseLocation(in: view)
        labelText.text = location.debugDescription
    }
}
4

1 回答 1

5

我最近遇到了从我的 PKCanvasView 获取触摸坐标的相同问题。为此,我创建了 PKCanvasView 的子类并覆盖了 touchesBegan 函数:

class Canvas: PKCanvasView {

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    touches.forEach { touch in
      print("touch location \(touch.location(in: self))")
    }
  }

}
于 2020-06-30T21:16:27.567 回答