How to draw a line in the simplest way in 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.
Solution 1:
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.
Solution 2:
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()
}