Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // DrawableView.swift
- // Drawing
- //
- // Created by Taichi Tsuchida on 2017/03/22.
- // Copyright © 2017 Taichi Tsuchida. All rights reserved.
- //
- import UIKit
- class DrawableView: UIView {
- /*
- // Only override draw() if you perform custom drawing.
- // An empty implementation adversely affects performance during animation.
- override func draw(_ rect: CGRect) {
- // Drawing code
- }
- */
- // override func draw(_ rect: CGRect) {
- //
- // }
- class Line {
- var points: [CGPoint]
- var color :CGColor
- var width: CGFloat
- init(color: CGColor, width: CGFloat){
- self.color = color
- self.width = width
- self.points = []
- }
- func drawOnContext(context: CGContext){
- UIGraphicsPushContext(context)
- context.setStrokeColor(self.color)
- context.setLineWidth(self.width)
- context.setLineCap(CGLineCap.round)
- // 2点以上ないと線描画する必要なし
- if self.points.count > 1 {
- for (index, point) in self.points.enumerated() {
- if index == 0 {
- context.move(to: CGPoint(x:point.x, y:point.y))
- } else {
- context.addLine(to: CGPoint(x:point.x, y:point.y))
- }
- }
- }
- context.strokePath()
- UIGraphicsPopContext()
- }
- }
- var lines: [Line] = []
- var currentLine: Line? = nil
- // タッチされた
- override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
- let point = touches.first!.location(in: self)
- currentLine = Line(color: UIColor.red.cgColor, width: 5)
- currentLine?.points.append(point)
- }
- // タッチが動いた
- override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
- let point = touches.first!.location(in: self)
- currentLine?.points.append(point)
- self.setNeedsDisplay()
- }
- // タッチが終わった
- override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
- // 2点以上のlineしか保存する必要なし
- if (currentLine?.points.count)! > 1 {
- lines.append(currentLine!)
- }
- currentLine = nil
- self.setNeedsDisplay()
- }
- func resetContext(context: CGContext) {
- context.clear(self.bounds)
- if let color = self.backgroundColor {
- color.setFill()
- } else {
- UIColor.white.setFill()
- }
- context.fill(self.bounds)
- }
- //描画設定
- override func draw(_ rect: CGRect) {
- let context = UIGraphicsGetCurrentContext()
- //画面を一旦初期化
- resetContext(context: context!)
- // 描き終わったline
- for line in lines {
- line.drawOnContext(context: context!)
- }
- // 描いてる途中のline
- if let line = currentLine {
- line.drawOnContext(context: context!)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement