I've been working in an app which I have to capture user's touches and draw a line on the screen. This is working so far.
The problem is that I'd like to create some kind of extension for that line that goes from the line start/end to the screen boundaries. It's important to that extension be aligned to the main line.
I've been trying to accomplish this for some days but without positive results. My idea was to use some kind of linear equation to represent the line and after create two point lying on the line and on the screen boundaries. The first problem I faced was with vertical lines.
y = m * x + b
slope = (y2 - y2)/(x2 - x1)
y_intercept = b = y - m * x
Also the user can create lines in any direction and orientation.
I tried to use these equations to find arbitrary points (x = 0, y = 0, x = 320, y = 480) but I got some strange issues like in the figures bellow.
a) Lines going really further the limit of the screen. This caused the app almost crash.
b) Also I couldn't identify how to link each new point with the current touch points.
Code
import Foundation
import UIKit
public class TestView : UIView
{
var lineLayer : CAShapeLayer?
var lineExtensionALayer : CAShapeLayer?
var lineExtensionBLayer : CAShapeLayer?
var startPoint : CGPoint?
var endPoint : CGPoint?
override init(frame: CGRect){
super.init(frame:frame)
self.backgroundColor = UIColor.clearColor()
self.lineLayer = self.createLine(color: UIColor.redColor())
self.lineExtensionALayer = self.createLine(color: UIColor.greenColor())
self.lineExtensionBLayer = self.createLine(color: UIColor.blueColor())
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let touch : UITouch = touches.first as! UITouch
let position = touch.locationInView(self)
self.startPoint = position
}
public override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
}
public override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
}
public override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
let touch : UITouch = touches.first as! UITouch
let position = touch.locationInView(self)
self.endPoint = position
self.updateLine()
}
func createLine(color selectedColor : UIColor) -> CAShapeLayer
{
let line = CAShapeLayer()
line.frame = self.bounds
line.strokeColor = selectedColor.CGColor
line.fillColor = nil
line.lineWidth = 2
self.layer.addSublayer(line)
return line
}
func drawLine(line lineToDraw : CAShapeLayer,start pointA : CGPoint, end pointB : CGPoint)
{
let path = UIBezierPath()
path.moveToPoint(pointA)
path.addLineToPoint(pointB)
lineToDraw.path = path.CGPath
}
func updateLine(){
var line = LineFunction(point1: self.startPoint!, point2: self.endPoint!)
// Draw main line.
self.drawLine(line: self.lineLayer!, start: self.startPoint!, end: self.endPoint!)
}
}