Search code examples
drawswift3drawrectnsbezierpathnscolor

Multiple colors drawn for NSBezierPath in cycle


I have following code in func draw(_ dirtyRect: NSRect) method but all the lines are drawn with the same color even if it should be randomized. I read that it may has something to do with fps but is there any way how to draw it multicolored? Thanks for any hint.

for y in 1...3 {
    for x in 1...20 {
        switch arc4random_uniform(5) {
            case 0:
                color = NSColor.red
            case 1:
                color = NSColor.purple
            case 2:
                color = NSColor.green
            case 3:
                color = NSColor.blue
            case 4:
                color = NSColor.yellow
            default:
                color = NSColor.yellow
            }
            point.move(to: NSPoint(x: x*10, y: y))
            point.line(to: NSPoint(x: x*10, y: y+100))
            color.setStroke()
            point.stroke()    
     }
}

Solution

  • Finally I found the solution or at least workaround - I put declaration of

       let point = NSBezierPath()
    

    into inner "x" loop and it works as expected. Not sure if it`s the mos efficient and proper solution so any further suggestions are welcome.