【问题标题】:Draw a line to connect two circles画一条线来连接两个圆
【发布时间】:2015-09-29 09:28:46
【问题描述】:

我正在构建一个自定义的用户界面输入,让用户通过一条线将两个圆圈相互连接。

这就是原型的样子

我想知道如何画直线?界面视图?精灵套件?还是什么?

【问题讨论】:

标签: ios swift uiview quartz-2d


【解决方案1】:

您应该使用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)
}

【讨论】:

  • 谢谢。此函数将在两点之间绘制静态线。我正在寻找要从一个点拉到另一个点的 交互式线
  • 那么,要每帧绘制,同时从起点拖动到当前点,您的手指所在的位置?
【解决方案2】:

没有缓存版本:

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)
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2018-05-02
    • 1970-01-01
    • 2011-06-06
    • 2012-08-15
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    • 1970-01-01
    相关资源
    最近更新 更多