Skip to content

Instantly share code, notes, and snippets.

@pvroosendaal
Last active March 31, 2019 22:27
Show Gist options
  • Save pvroosendaal/f1617fe7e164bc94f0d37d3175252e2f to your computer and use it in GitHub Desktop.
Save pvroosendaal/f1617fe7e164bc94f0d37d3175252e2f to your computer and use it in GitHub Desktop.
Draw dynamic line path - sample
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class CustomButton: UIButton {
var key: String?
convenience init(key: String, point: CGPoint) {
self.init(type: .custom)
self.key = key
self.frame.size = CGSize(width: 16, height: 16)
self.center = point
self.backgroundColor = .black
self.layer.masksToBounds = true
self.layer.cornerRadius = 8.0
}
}
class MyViewController : UIViewController {
let points = [
("A", CGPoint(x: 20, y: 400)),
("B", CGPoint(x: 50, y: 350)),
("C", CGPoint(x: 80, y: 350)),
("D", CGPoint(x: 110, y: 300)),
("E", CGPoint(x: 200, y: 400)),
("F", CGPoint(x: 230, y: 375)),
]
var startKey: String?
var endKey: String?
var activeLineImageView: UIImageView?
override func loadView() {
let view = UIView()
view.backgroundColor = .white
view.frame.size = CGSize(width: 500, height: 500)
self.view = view
UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0)
let path = UIBezierPath()
path.lineWidth = 5.0
path.move(to: points[0].1)
points.forEach { point in
let button = CustomButton(key: point.0, point: point.1)
button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
view.addSubview(button)
path.addLine(to: point.1)
}
UIColor.black.setStroke()
path.stroke()
var image = UIGraphicsGetImageFromCurrentImageContext()
var imageView = UIImageView(image: image)
self.view.addSubview(imageView)
UIGraphicsEndImageContext()
}
@objc private func buttonPressed(_ button: CustomButton) {
if startKey == nil && endKey == nil {
activeLineImageView?.removeFromSuperview()
activeLineImageView = nil
startKey = button.key
return
}
if startKey != nil && endKey == nil {
endKey = button.key
drawLine()
resetKeys()
}
}
private func drawLine() {
UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0)
let path = UIBezierPath()
path.lineWidth = 3.0
var add = false
for point in points {
if let startKey = startKey, startKey == point.0 {
path.move(to: point.1)
add = true
continue
}
if let endKey = endKey, endKey == point.0 {
path.addLine(to: point.1)
add = false
break
}
if add {
path.addLine(to: point.1)
continue
}
}
UIColor.red.setStroke()
path.stroke()
var image = UIGraphicsGetImageFromCurrentImageContext()
activeLineImageView = UIImageView(image: image)
self.view.addSubview(activeLineImageView!)
UIGraphicsEndImageContext()
}
private func resetKeys() {
startKey = nil
endKey = nil
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment