Friday, April 29, 2011

What's the best way to draw a bunch of (~200) colored rectangles in Cocoa?

My current plan is to draw the rectangles by subclassing NSView, but that seems like a very inefficient way for what I'm trying to do, which is to draw a bunch of fixed, non-overlapping rectangles that changes colors once in a while. Is there a better way? Thanks.

From stackoverflow
  • You can try using CALayers, kind of like this: http://theocacao.com/document.page/555.

  • If they're all the same color or image, you may find a single CGLayer more efficient. The purpose of that API is drawing the same thing many times.

    On the other hand, if the rectangles move independently or have different colors or images on them, Core Animation is definitely the way to go.

  • Core Animation would be a great technology for a game, but if you want to stick with NSView for the time being you could create a class similar to NSCell that the gameboard view uses to implement positioning and drawing. This would work in a similar way as many Cocoa control classes, which use a single cell (with different values) to draw multiple items inside a view.

    Keep in mind that using individual NSView objects may very well be more than fast enough, but regardless of any speed differences this strategy allows you to separate the logic in a way that makes sense.

0 comments:

Post a Comment