Poor CGContextStrokePath performance when drawing multiple lines and circles on iPhone

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

I subclass (myView) from UIView and implement the 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 dog is slow. Is something missing here? It takes almost 1 second to complete one complete drawing.

+4
source share
1 answer

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

Instead, you need to create separate layers or views for each element to be animated. These layers or views will be drawn only once and then cached. When the layers move, they will not be redrawn, they are simply composed. Absolutely, even the slowest iOS devices (the original first-generation iPhone, iPhone 3G and iPod touch) can animate up to 100 levels at 60 frames per second.

Think of it as a cartoon animation. Instead of having the animators manually redraw each part of each frame, they use cells to reuse elements between frames that remain unchanged or simply move without changing shape. This greatly reduces the effort to create a cartoon.

+7
source

Source: https://habr.com/ru/post/1315211/


All Articles