views:

32

answers:

1

I need to draw a few hundred lines and circles on my view and they keep moving through a timer function, where I call [myView setNeedsDisplay] to update the view.

I subclass (myView) from UIView and implement drawRect function to do the following ...

-(void) drawRect:(CGRect)rect {
   CGContextRef context = UIGraphicsGetCurrentContext();

   CGFloat red[4] = { 1, 0, 0, 1};

   CGContextSetLineWidth(context, 1);
   CGContextSetShouldAntialias(context, NO);
   CGContextSetLineCap(context, kCGLineCapSquare);
   CGContextSetStrokeColor(context, red);

   // rects is an array of CGRect of size ~200
   for (int i = 0; i < N; i++) {
      CGContextAddEllipseInRect(context, rects[i]);
   }
   // points is an array of CGPoint of size ~100
   CGContextAddLines(context, points, N);

   CGContextStrokePath(context, color);
}

But this is dog slow. Is there something I am missing here? It is taking almost 1 sec to do one complete drawing

+2  A: 

Animating objects by redrawing them constantly is a bad way to go. Quartz drawing is one of the slowest things you can do, UI-wise, because of the way that the display system works.

Instead, what you will want to do is create individual layers or views for each element that will be animated. These layers or views will only be drawn once, and then cached. When the layers move around, they won't be redrawn, just composited. Done this way, even the slowest iOS devices (the original iPhone, iPhone 3G, and first generation iPod touch) can animate up to 100 layers at 60 frames per second.

Think of it like animating a cartoon. Rather than have the animators redraw by hand every part of every frame, they use cells to reuse elements between frames that stay the same or just move without changing form. This significantly reduces the effort of producing a cartoon.

Brad Larson
Thanks Brad for your quick reply. However, my problem here is that in each iteration, my algorithm can return random geometric shapes, so it is kind of difficult to pre-draw them and then move them around. I am sure there will be way to do even that. But for now I have found a workaround, draw all my stuff in a raw memory buffer and convert it all the way to UIImage, and display it. That seems to much faster.
Pankaj