Swift PencilKitでポイントした先に四角を描画

手帳「アクションプランナー」→「Planner」→オリジナル開発(APCDigital)→標準化「Refill Calendar」つづき1
の標準化前「APCDigital」に、タスクチェックボックスをスタンプする機能を追加。
その先はRefill Calendarへの反映を検討。

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) {
            print("x:\(location.x) y:\(location.y)")
            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
            }
        }
        self.drawing.strokes.append(contentsOf: strokes)
    }
}

Swift

Posted by shi-n