【发布时间】:2015-08-02 18:28:08
【问题描述】:
我一直在开发一个应用程序,我必须捕捉用户的触摸并在屏幕上画一条线。到目前为止,这是有效的。
问题是我想为从行开始/结束到屏幕边界的那条线创建某种扩展。扩展名必须与主线对齐。
我这几天一直在努力实现这一目标,但没有取得积极成果。我的想法是使用某种线性方程来表示线条,然后在线条和屏幕边界上创建两个点。我遇到的第一个问题是垂直线。
y = m * x + b
slope = (y2 - y2)/(x2 - x1)
y_intercept = b = y - m * x
我尝试使用这些方程来找到任意点(x = 0,y = 0,x = 320,y = 480),但我遇到了一些奇怪的问题,如下图所示。
代码
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!)
}
}
【问题讨论】:
标签: ios math drawing core-graphics line