2016-12-15 38 views
1

我想用UIBezierpath在UIView上畫一條線。我認爲我錯過了一些東西,但無法找到答案。用UIBezierPath在Swift 3.x中畫一條線

這裏是我的代碼:

// Code for touch recognition 
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    swiped = false 
    if let touch = touches.first as? UITouch? { 
     lastPoint = (touch?.location(in: fullview))! 
     //print(lastPoint) 
    } 
} 

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { 
    swiped = true 
    if let touch = touches.first as? UITouch? { 
     let currentPoint = touch?.location(in: fullview) 
     drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint!) 

     lastPoint = currentPoint! 
     //print(lastPoint) 
     //print("touch moved") 
    } 
} 

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
    if !swiped { 
     drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint) 
    } 
    //print("touch ended") 
} 

//code for drawing 
func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint){ 

    UIGraphicsBeginImageContext(fullview.frame.size) 

    let context = UIGraphicsGetCurrentContext() 

    let aPath = UIBezierPath() 

    //aPath.move(to: fromPoint) 
    //aPath.addLine(to: toPoint) 
    aPath.lineWidth=10.0 
    aPath.lineJoinStyle = .round 
    aPath.move(to: CGPoint(x:15,y:15)) 
    aPath.addLine(to: CGPoint(x:80,y:80)) 
    aPath.addClip() 
    aPath.close() 
    UIColor.green.set() 
    aPath.stroke() 

    //print("drawline") 
    //print("Frompoint = ",fromPoint) 
    //print("topoint = ",toPoint) 

    /* context?.setLineCap(.round) 
    context?.setLineWidth(brushWidth) 
    context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0) 
    context?.setBlendMode(.normal) 

    context?.beginPath() 
    context?.move(to: fromPoint) 
    context?.addLine(to: toPoint) 
    context?.closePath() 
    context?.strokePath()*/ 


    //let image = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 

    fullview.setNeedsDisplay() 
} 

正如你所看到的,我想這也與上下文,但它不是工作壓力太大。

謝謝你的幫助!

+0

[Check this](https://www.google.de/search?q=Drawing+a+line+in+Swift+3.x+with+UIBezierPath&ie=utf-8&oe=utf-8&client=firefox- b-ab&gfe_rd = cr&ei = 4K5SWNHCAq2o8weUg52YDg) – shallowThought

+0

谷歌是我的朋友:)我只是在尋找錯誤的關鍵字,thx –

+0

它實際上是你的確切標題:-) – shallowThought

回答

7

我使用它來畫一條線:

let doYourPath = UIBezierPath(rect: CGRect(x: xPos, y: yPos, width: yourWidth, height: yourHeight)) 
    let layer = CAShapeLayer() 
    layer.path = doYourPath.cgPath 
    layer.strokeColor = UIColor.white.cgColor 
    layer.fillColor = UIColor.white.cgColor 

    self.view.layer.addSublayer(layer) 

希望這有助於你出去。這只是一種迅速繪製線條的方法。

+0

這幫了我很多,謝謝 –

+0

歡迎您! –

2

那麼,你正在繪製一個圖像上下文(離屏位圖),而不是視圖。這很可能不是你想要的?確保您已閱讀iOS Drawing Concepts

UIView子類應該可能只是追蹤觸摸的位置(如在一個var touchedPositions = [CGPoint]())和呼叫setNeedsDisplay()。 然後在你的子類中實現func draw(_ rect: CGRect)方法。在此方法中,創建您的路徑並根據您跟蹤的位置繪製它(不創建新的上下文)。

+0

好吧,理解,thx –