Created
April 10, 2018 03:48
-
-
Save uruly/075ea291fbc58f7ceabdae3719616875 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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