Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a line in the simplest way in swift

Tags:

ios

swift

I am fairly new to swift and Xcode and I am trying to make a tic tac toe game. I have everything figured out except how to draw a line through the three x's or o's. I have no idea on how to draw lines. I have looked on the web for the answer and can't figure it out.

like image 857
Volkodav Avatar asked Jul 22 '15 16:07

Volkodav


People also ask

How do I make a circle in Swift?

With Border Color and Border Size and the default Background property you can define the appearance of the circle. Please note, to draw a circle the view's height and width have to be equal in size. The code is working for Swift >= 4 and Xcode >= 9 .


2 Answers

Try looking into UIBezierPath, it will help you a lot for drawing lines. Here is documentation. Here is an example:

override func drawRect(rect: CGRect) {     let aPath = UIBezierPath()      aPath.move(to: CGPoint(x:<#start x#>, y:<#start y#>))     aPath.addLine(to: CGPoint(x: <#end x#>, y: <#end y#>))      // Keep using the method addLine until you get to the one where about to close the path     aPath.close()      // If you want to stroke it with a red color     UIColor.red.set()     aPath.lineWidth = <#line width#>     aPath.stroke() } 

Make sure you put this code in the drawRect, like in the example above.

If you need to update the drawing just call setNeedsDisplay() to update.

like image 56
Epic Defeater Avatar answered Oct 23 '22 08:10

Epic Defeater


Update for Swift 3.x using Epic Defeater's example

override func draw(_ rect: CGRect) {         let aPath = UIBezierPath()          aPath.move(to: CGPoint(x:20, y:50))          aPath.addLine(to: CGPoint(x:300, y:50))          //Keep using the method addLineToPoint until you get to the one where about to close the path          aPath.close()          //If you want to stroke it with a red color         UIColor.red.set()         aPath.stroke()         //If you want to fill it as well         aPath.fill()     } 
like image 27
Sal Avatar answered Oct 23 '22 08:10

Sal