Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make the CGFloat array for setLineDash in Swift

Tags:

swift

cocoa

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

like image 666
o.uinn Avatar asked Jul 22 '14 04:07

o.uinn


2 Answers

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)
like image 176
Martin R Avatar answered Oct 11 '22 02:10

Martin R


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
    }
}
like image 1
Daniel Kuta Avatar answered Oct 11 '22 02:10

Daniel Kuta