いつもお世話になります。iPad Pro用のメモアプリを作成しようと考えています。
Apple pencilのswiftのサンプル。以下のサイトを見つけました。
https://www.raywenderlich.com/1407-apple-pencil-tutorial-getting-started
このサイトのサンプルがswift2でかかれたものでした。
swift4ようにソースを調整してみましたが、実行するとメモリーリークでうまく動作しません。
ViewControllerのviewDidLoadのcanvasView.clearCanvas(animated: false)でメモリリークとなります。
エラー内容 => Thread 1: EXC_BAD_ACCESS (code=257, address=0x1a1b6f04ec9)
よくわからないので、誰かご教授をお願いできなでしょうか。
// ViewCotroller.swift
import UIKit class ViewController: UIViewController { @IBOutlet weak var canvasView: CanvasView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. canvasView.clearCanvas(animated: false) } // Shake to clear screen override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { canvasView.clearCanvas(animated: true) } }
// CanvasView.swift
import Foundation import UIKit let π = CGFloat(Double.pi) class CanvasView: UIImageView { // Parameters private let defaultLineWidth:CGFloat = 6 private var drawColor: UIColor = UIColor.red override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return } UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0) let context = UIGraphicsGetCurrentContext() // Draw previous image into context image?.draw(in: bounds) drawStroke(context: context, touch: touch) // Update image image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } private func drawStroke(context: CGContext?, touch: UITouch) { let previousLocation = touch.previousLocation(in:self) let location = touch.location(in:self) // Calculate line width for drawing stroke let lineWidth = lineWidthForDrawing(context: context, touch: touch) // Set color drawColor.setStroke() // Configure line context?.setLineWidth(CGFloat(Double(lineWidth))) context?.setLineCap(.round) // Set up the points context?.move(to: CGPoint(x: previousLocation.x, y: previousLocation.y)) context?.addLine(to: CGPoint(x: location.x, y: location.y)) // Draw the stroke context?.strokePath() } private func lineWidthForDrawing(context: CGContext?, touch: UITouch) -> CGFloat { let lineWidth = defaultLineWidth return lineWidth } func clearCanvas(animated: Bool) { if animated { UIView.animate(withDuration: 0.5, animations: { self.alpha = 0 }, completion: { finished in self.alpha = 1 self.image = nil }) } else { image = nil } } }
回答1件
あなたの回答
tips
プレビュー