2016-11-11 24 views
7

में एक रेखा को कैसे आकर्षित करें मैं उपयोगकर्ता को 2 अंक स्पर्श करना चाहता हूं और फिर उन दो बिंदुओं के बीच एक रेखा खींची जाती है। यहाँ मैं अब तक है:स्विफ्ट 3

func drawline(){ 
    let context = UIGraphicsGetCurrentContext() 
    context!.beginPath() 
    context?.move(to: pointA) 
    context?.addLine(to: pointB) 
    context!.strokePath() 
} 

pointA पहला बिंदु उपयोगकर्ता को छुआ है और pointB दूसरी बात है। मुझे त्रुटि मिलती है:

thread 1:EXC_BREAKPOINT 

आपकी सहायता के लिए अग्रिम धन्यवाद।

उत्तर

15

दो बिंदुओं के बीच एक रेखा खींचने के लिए आपको पहली चीज़ की आवश्यकता है CGPoints वर्तमान UIView से प्राप्त करें, इसे प्राप्त करने के कई तरीके हैं। जब आप टैप करते हैं तो पता लगाने के लिए नमूना के लिए मैं UITapGestureRecognizer का उपयोग करने जा रहा हूं।

एक और चरण एक बार आपके पास दो बिंदुओं के बीच की रेखा को सहेजने के बाद दो बिंदुओं को खींच लिया जाता है, और इसके लिए आप ग्राफिक्स संदर्भ का उपयोग कर सकते हैं जैसे आप पहले कोशिश करते हैं या CAShapeLayer का उपयोग करते हैं।

तो समझाया अनुवाद ऊपर हम निम्नलिखित कोड प्राप्त:

class ViewController: UIViewController { 

    var tapGestureRecognizer: UITapGestureRecognizer! 

    var firstPoint: CGPoint? 
    var secondPoint: CGPoint? 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.showMoreActions(touch:))) 
     tapGestureRecognizer.numberOfTapsRequired = 1 
     view.addGestureRecognizer(tapGestureRecognizer) 
    } 

    func showMoreActions(touch: UITapGestureRecognizer) { 
     let touchPoint = touch.location(in: self.view) 

     guard let _ = firstPoint else { 
      firstPoint = touchPoint 
      return 
     } 

     guard let _ = secondPoint else { 
      secondPoint = touchPoint 
      addLine(fromPoint: firstPoint!, toPoint: secondPoint!) 

      firstPoint = nil 
      secondPoint = nil 

      return 
     } 
    } 

    func addLine(fromPoint start: CGPoint, toPoint end:CGPoint) { 
     let line = CAShapeLayer() 
     let linePath = UIBezierPath() 
     linePath.move(to: start) 
     linePath.addLine(to: end) 
     line.path = linePath.cgPath 
     line.strokeColor = UIColor.red.cgColor 
     line.lineWidth = 1 
     line.lineJoin = kCALineJoinRound 
     self.view.layer.addSublayer(line) 
    } 
} 

ऊपर कोड एक लाइन हर बार दो अंक चुने गए हैं आकर्षित करने के लिए जा रहा है और के रूप में आप की तरह आप ऊपर समारोह अनुकूलित कर सकते हैं।

मुझे उम्मीद है कि यह आपकी मदद करेगा।

+0

धन्यवाद! मेरे पास एक और सवाल है: मैं उन रेखाओं को कैसे हटा सकता हूं जिन्हें उपयोगकर्ता ने –

+1

@ चार्ल्स बी खींचा है। आपका स्वागत है, आप संदर्भों को सहेजने वाले पिछले 'सीएएसएचएपीएलएयर' ('removeFromSuperlayer' के साथ) को हटा सकते हैं, यह –

+0

@ विक्टर करने का एक तरीका है, मैंने आपकी func addline का उपयोग किया और यह एक सेल के अंदर एक रेखा खींचने के लिए काम करता है। धन्यवाद –