【问题标题】:How to Get the Coordinates of a Touch Gesture on a PKCanvasView using PencilKit? Swift 5 & Xcode 11如何使用 PencilKit 在 PKCanvasView 上获取触摸手势的坐标?斯威夫特 5 和 Xcode 11
【发布时间】:2020-03-04 16:09:33
【问题描述】:

请注意,我到处寻找,但找不到解决方案。

使用 Storyboard,我有一个 ViewController,带有一个 View (UIView) 和一个 Subview ( PKCanvasView),我想使用 PencilKit 在后者上绘图。

_

我的目标是:

  1. 绘图只在这个PKCanvasView

  2. 实时获取我在 PKCanvasView

  3. 上绘制位置的坐标

我的结果

  1. 只有从这个视图开始,我才能在 PKCanvasView 上绘制,而且我只能在这个 PKCanvasView 的框架内绘制时间>。这很好。

  2. 我只能管理获取我触摸屏幕位置的坐标如果我在 UIView上开始手势>。 但不是,如果我先触摸 PKCanvasView

我的问题

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

-

下面是我的代码

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

【问题讨论】:

    标签: ios swift xcode pencilkit


    【解决方案1】:

    我最近遇到了从我的 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))")
        }
      }
    
    }
    

    【讨论】:

    • 我还没有尝试过,但大概画布视图需要触摸方法来实际进行绘图,如果你覆盖它们,那么所有这些功能不会丢失吗?
    • 在自己的实现前加上:super.touchesBegan(touches, with: event),继承的功能也会被调用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2017-03-24
    • 1970-01-01
    相关资源
    最近更新 更多