Swift PencilKitでポイントした先に四角を描画、指入力時排除

ベース

手帳「アクションプランナー」→「Planner」→オリジナル開発(APCDigital)→標準化「Refill Calendar」つづき1
の標準化前「APCDigital」

四角描画対応

Swift PencilKitでポイントした先に四角を描画
Swift PencilKitでポイントした先に四角を描画、Undo対応してみた

課題

Apple Pencilだけのつもりが、指入力でも四角が描画される。

pKCanvasView.drawingPolicy = .pencilOnly

指定をしても、
override func touchesBegan(_ touches: Set, with event: UIEvent?)
はコールされる。

解決方法

UITouchのtypeで判断する。
https://developer.apple.com/documentation/uikit/uitouch/touchtype

アプリ

APCDigitalhttps://github.com/cloudsquare22/APCDigital

Refill Calendar

Download on the App Store

ラップしたPKCanvasView(指入力解決版)

動作させた結果、strokeRectangle()をコールしなければ、通常のPencil描画が動作する。
strokeRectangle()をした場合はこちらが優先になる。

import UIKit
import PencilKit

class RapPKCanvasView: PKCanvasView {
    
    var onTaskbox: Bool = false
    var taskBoxColor: UIColor = .black

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard self.onTaskbox == true else {
            return
        }
        print(#function)
        let touch = touches.first
        if let location = touch?.location(in: self), let type = touch?.type {
            print("type:\(type)")
            print("x:\(location.x) y:\(location.y)")
            if type == .pencil {
                self.strokeRectangle(location: location)
            }
        }
    }

    func strokeRectangle(location: CGPoint) {
        let size: CGFloat = 8
        let x = location.x - (size / 2)
        let y = location.y - (size / 2)
        let pointArrays = [
            [CGPoint(x: x, y: y),
             CGPoint(x: x + size, y: y),
             CGPoint(x: x + size, y: y + size),
             CGPoint(x: x, y: y + size),
             CGPoint(x: x, y: y)],
        ]
        let ink = PKInk(.pen, color: self.taskBoxColor)
        var strokes: [PKStroke] = []

        for points in pointArrays where points.count > 1 {
            let strokePoints = points.enumerated().map { index, point in
                PKStrokePoint(location: point, timeOffset: 0.1 * TimeInterval(index), size: CGSize(width: 2.6, height: 2.6), opacity: 2, force: 1, azimuth: 0, altitude: 0)
            }

            var startStrokePoint = strokePoints.first!

            for strokePoint in strokePoints {
                let path = PKStrokePath(controlPoints: [startStrokePoint, strokePoint], creationDate: Date())
                strokes.append(PKStroke(ink: ink, path: path))
                startStrokePoint = strokePoint
            }
        }
        print("strokes:\(strokes.count)")
        self.drawing.strokes.append(contentsOf: strokes)
        
        self.undoManager!.registerUndo(withTarget: self, selector: #selector(undoStrocke), object: self.drawing.strokes)
    }
    
    @objc func undoStrocke() {
        for _ in 1...5 {
            self.drawing.strokes.removeLast()
        }
    }
    
}

SwiftSwift

Posted by shi-n