drawRect function hindering performance
I am working on drawing a snake which moves using a CADisplayLink using DrawRect.
The problem is when the snake is small the speed is fine, but when the snake grows in length the snake becomes really slow.
I keep track of the snake using the followig variables:
- variable to keep trac开发者_开发百科k of snakes head - variable to keep track of snakes tail - variable to keep track of snakes head direction - variable to keep track of snakes tail direction - Array with all the points the snake bends - Array to keep track of direction of each bendBelow is the code i am using to draw the snake.
-(void)drawRect:(CGRect)rect{
CGContextBeginPath(context);
CGContextSetLineWidth(context, 10.0);
float glowWidth = 10.0;
float colorValues[] = {0.4,0.4,0.4,1.0};
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGColorRef glowColor = CGColorCreate(colorspace, colorValues);
CGContextSetShadowWithColor(context, CGSizeMake(0.0, 0.0), glowWidth, glowColor);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetStrokeColorWithColor(context,[UIColor blackColor].CGColor);
GContextMoveToPoint(context, snake.tail_x,snake.tail_y);
for (int i = 0; i < [snake.bends count]; i++) {
NSData *bend_dir_value = [snake.bend_direction objectAtIndex:i];
Direction bend_dir = * (Direction *)[bend_dir_value bytes];
NSData *bend_value = [snake.bends objectAtIndex:i];
CGPoint bend_point = * (CGPoint * )[bend_value bytes];
if (bend_dir == kEastIn || bend_dir == kWestIn || bend_dir == kNorthIn || bend_dir == kSouthIn) {
CGContextMoveToPoint(context, bend_point.x, bend_point.y);
}
else {
CGContextAddLineToPoint(context, bend_point.x, bend_point.y);
}
}
CGContextAddLineToPoint(context, snake.head_x, snake.head_y);
}
Why is my performance being so bad when the snake lengths/bend increases?
Is there another way i should be drawing the snake?
Could it be that you're not closing your path? Right at the end you might need:
CGContextClosePath(context);
Have you profiled your app to figure out where most of the time is spent when it slows down?
It could be in the path stroke in core graphics, in your computational methods, or somewhere else. If you start optimizing before you have any profile/performance data, you may end up spending time in the wrong place.
精彩评论