Regan
Regan

Reputation: 1497

Efficiently drawing and animating thousands of rectangles

What I am trying to do is to have many small rectangles on the screen (up to several thousand) which move randomly.

I have the mechanics behind this figured out (in terms of determining the coordinates for the movement), but I can't figure out the best way to draw the shapes or model their movement.

A couple strategies I have tried have been, first, to subclass NSView (this is on the Mac) and create thousands of these. I then change their drawRect: function in order to draw a square inside of themselves. Then it is pretty simple to just change their locations to move them around. However, with several thousand allocated instances of these, performance is obviously terrible.

I tried a less object-oriented route also, just using NSRectFill to draw the thousands of rectangles. However, I had trouble implementing the movement I needed with this, though it was blazing fast.

Does anyone have any suggestions on how I could successfully create this animation?

Upvotes: 2

Views: 453

Answers (2)

Ryan
Ryan

Reputation: 16636

Several thousand rectangles may be too much for CoreAnimation. You should consider using OpenGL.

Upvotes: 1

Joshua Nozzi
Joshua Nozzi

Reputation: 61248

Layers and Core Animation are the best approach for the platform.

Upvotes: 2

Related Questions