2016-12-06 211 views
1

我正在研究一個項目,我希望如果用戶觸摸沿水平方向移動,那麼水平線應該繪製並且用戶觸摸沿垂直方向移動,然後垂直線應該繪製。請建議使用Swift的一些解決方案。 我在下面試過。但是這是免費的。在iOS中使用觸摸繪製水平線或垂直線

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 

     super.touchesBegan(touches, with: event) 

     let touch: AnyObject? = touches.first 
     let lastPoint = touch!.previousLocation(in: holderView) 
     path.move(to: CGPoint(x: lastPoint.x, y: lastPoint.y)) 

    } 

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { 

     super.touchesMoved(touches, with: event) 

     let touch: AnyObject? = touches.first 
     let currentPoint = touch!.location(in: holderView) 

     path.addLine(to: CGPoint(x: currentPoint.x, y: currentPoint.y)) 

     //Design path in layer 
     let shapeLayer = CAShapeLayer() 
     shapeLayer.path = path.cgPath 
     shapeLayer.strokeColor = UIColor.orange.cgColor 
     shapeLayer.lineWidth = 20.0 

     holderView.layer.addSublayer(shapeLayer) 

} 

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 

     super.touchesEnded(touches, with: event) 
     path=UIBezierPath() 
    } 
+0

可以通過這個鏈接http://stackoverflow.com/questions/4669490/how-to-draw-line-on-touch-event –

+0

什麼,如果用戶觸摸屏幕,並創建一個曲線路徑點數? –

+0

太多未知數!你的代碼說:「有一條更加緩慢的路徑,當觸摸開始時,跳到觸摸位置,當觸摸移動時,畫線到新的位置並在新的子圖層中顯示結果,當觸摸結束時,創建一個新的貝塞爾路徑」 。子層邏輯看起來效率極低(創建數百個部分重複的子層),而且更復雜的路徑創建似乎不必要地倒退,但除此之外。鑑於上述邏輯的解釋,你能否澄清你想達到的目標? – Baglan

回答

0

試試這個。

class DrawingView: UIView { 
    var path = UIBezierPath() 
    var initialLocation = CGPoint.zero 
    var finalLocation = CGPoint.zero 
    var shapeLayer = CAShapeLayer() 

    override func awakeFromNib() { 
     super.awakeFromNib() 
     setupView() 
    } 

    override init(frame: CGRect) { 
     super.init(frame: frame) 
     setupView() 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    func setupView(){ 
     self.layer.addSublayer(shapeLayer) 
     self.shapeLayer.lineWidth = 20 
     self.shapeLayer.strokeColor = UIColor.blue.cgColor 
    } 


    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
     super.touchesBegan(touches, with: event) 
     if let location = touches.first?.location(in: self){ 
      initialLocation = location 
     } 
    } 

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { 
     super.touchesMoved(touches, with: event) 

     if let location = touches.first?.location(in: self){ 
      let dx = location.x - initialLocation.x 
      let dy = location.y - initialLocation.y 

      finalLocation = abs(dx) > abs(dy) ? CGPoint(x: location.x, y: initialLocation.y) : CGPoint(x: initialLocation.x, y: location.y) 

      path.removeAllPoints() 
      path.move(to: initialLocation) 
      path.addLine(to: finalLocation) 

      shapeLayer.path = path.cgPath 

     } 
    } 
}