How can I override the drawRect method of UIView such that each time I call [myView setNeedsDisplay] it will draw a new random circle on the screen with a random color. It should not replace old circles. So, it should just look like a bunch of circles stacking up all over the screen, one after another.
Share
You can’t use
drawRect:in this way. It is designed to draw the entire view inside that rect, so you would have to draw all of the balls at once, not just the ball you’re adding. Every time drawRect is called, the area of the screen you are drawing into has already been wiped of it’s previous state.My initial thought was to create a view for each individual ball, with a random size and position. But the SonOfSillyBalls example code (which does exactly what you’re trying to do) takes a different approach.
It’s
NSViewsubclass sets a repeating timer to fire adrawAnother:method, which does[self lockFocus], then draws a random ball, and then[self unlockFocus]to finish drawing. Finally, it calls[self.window flushWindow]to get the new ball onto the screen.Since it does exactly what you’re trying to do, perhaps you shouldn’t read it (where’s the challenge in that!), but the sample code for SonOfSillyBalls is here: http://developer.apple.com/library/mac/#samplecode/SonOfSillyBalls/
You might want to check out the read me for an explanation of the overall problem and why it’s not an ideal fit for modern drawing APIs (note: it’s old, so in places it refers to Mac OS X as “Open Step” and “Rhapsody” (the “X” name hadn’t been invented yet) and Classic Mac OS just as “Mac OS”)
Silly Balls is one of Apple’s oldest pieces of sample code, originally from back in the 1980’s, but this is the third (i think?) revision, updated only six months ago to use Objective-C 2.0.