Skip to content

Instantly share code, notes, and snippets.

@uruly
Created April 10, 2018 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uruly/075ea291fbc58f7ceabdae3719616875 to your computer and use it in GitHub Desktop.
Save uruly/075ea291fbc58f7ceabdae3719616875 to your computer and use it in GitHub Desktop.
import UIKit
class ViewController: UIViewController {
var bezierPath:UIBezierPath!
var canvas:UIImageView!
var lastDrawImage:UIImage?
override func viewDidLoad() {
super.viewDidLoad()
let width = self.view.frame.width
let height = self.view.frame.height
//キャンバスを設置
canvas = UIImageView()
canvas.frame = CGRect(x:0,y:0,width:width,height:height)
canvas.backgroundColor = UIColor.clear
self.view.addSubview(canvas)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touchEvent = touches.first!
let currentPoint:CGPoint = touchEvent.location(in: self.canvas)
bezierPath = UIBezierPath()
bezierPath.lineWidth = 4.0
bezierPath.lineCapStyle = .butt
bezierPath.move(to:currentPoint)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if bezierPath == nil {
return
}
let touchEvent = touches.first!
let currentPoint:CGPoint = touchEvent.location(in: self.canvas)
bezierPath.addLine(to: currentPoint)
drawLine(path: bezierPath)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if bezierPath == nil {
return
}
let touchEvent = touches.first!
let currentPoint:CGPoint = touchEvent.location(in: canvas)
bezierPath.addLine(to: currentPoint)
drawLine(path: bezierPath)
self.lastDrawImage = canvas.image
}
//描画処理
func drawLine(path:UIBezierPath){
UIGraphicsBeginImageContext(canvas.frame.size)
if let image = self.lastDrawImage {
image.draw(at: CGPoint.zero)
}
let lineColor = UIColor.black
lineColor.setStroke()
path.stroke()
self.canvas.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment