我正在构建一个自定义的用户界面输入,让用户通过一条线连接两个圆圈。
这就是原型的样子
我想知道怎么画直线? UIViews? SpriteKit?或者什么?
答案 0 :(得分:0)
您应该使用UIBezierPath()
和CAShapeLayer()
。
func drawLineFromPoint(point1:CGPoint, point2:CGPoint) {
let path = UIBezierPath()
path.moveToPoint(point1)
path.addLineToPoint(point2)
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.CGPath
shapeLayer.strokeColor = UIColor.greenColor().CGColor
shapeLayer.lineWidth = 1
shapeLayer.fillColor = UIColor.clearColor().CGColor
self.view.layer.addSublayer(shapeLayer)
}
答案 1 :(得分:0)
没有缓存版本:
class LineView:UIView {
var startP: CGPoint?
var endP: CGPoint?
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first
let location = touch?.locationInView(self);
//do some matching here...
self.startP = location
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first
let location = touch?.locationInView(self);
self.endP = location
self.setNeedsDisplay()
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first
let location = touch?.locationInView(self);
//do some matching here...
self.endP = location
self.setNeedsDisplay()
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
if let start = self.startP {
if let end = self.endP {
CGContextMoveToPoint(context, start.x, start.y)
CGContextAddLineToPoint(context, end.x, end.y)
CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor)
CGContextStrokePath(context)
}
}
}
}