I want to make a dashed line using swift. Like this...
var path = NSBezierPath()
path.moveToPoint(NSPoint(x: 1, y: 1))
path.moveToPoint(NSPoint(x: 4, y: 4))
let pattern: ConstUnsafePointer<CGFloat> = {1.0, 1.0} //Not sure how to write this
path.setLineDash(pattern, count: 2, phase: 0.0)
path.stroke()
My question is how to make the c array of CGFloats
An array of CGFloats can be defined as
let pattern: [CGFloat] = [5.0, 5.0]
Note that you have to use moveToPoint
+ lineToPoint
to draw a line:
var path = NSBezierPath()
path.moveToPoint(NSPoint(x: 1, y: 1))
path.lineToPoint(NSPoint(x: 40, y: 40))
let pattern: [CGFloat] = [5.0, 5.0]
path.setLineDash(pattern, count: 2, phase: 0.0)
This code below create dashed line in Swift 2. Paste this into new class and extend to UIView.
override public func drawRect(rect: CGRect) {
super.drawRect(rect)
checkLineOrientation(rect)
let context = UIGraphicsGetCurrentContext()
CGContextSetStrokeColorWithColor(context, lineColor.CGColor)
CGContextSetLineWidth(context, lineWidth)
let lines = [CGPointMake(0, 0), CGPointMake(posX, posY)]
let pattern: [CGFloat] = [lineLength, lineSpace]
CGContextSetLineDash(context, 2, pattern, 2);
CGContextAddLines(context, lines, 2)
CGContextStrokePath(context)
}
// Horizontal or vertical line position
func checkLineOrientation(rect: CGRect) {
if rect.width > rect.height {
lineWidth = rect.height
posX = rect.width
posY = 0
} else {
lineWidth = rect.width
posX = 0
posY = rect.height
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With