NemesisII
NemesisII

Reputation: 21

UIImage drawInRect:rect is too slow

I want to write a simple program like: If an user enters a number N (N < 100) then I draw N fish on the screen at random position on a UIView. I use the drawInRect but it's very slow. It takes about 10 ms to draw a 21 x 16 px image ON REAL DEVICE...so 100 fish will cost me about 1 second. I need a much faster approach (about 1ms per fish)

Is there any other way? I don't want to use Open GL b/s I need to do a lot of things with UIKIT....

this is My Draw Function:

void FishDraw(float px, float py)
{
    CGRect rect;


    NSDate *start = [NSDate date];
    rect.size.width = fishimg.size.width;
    rect.size.height = fishimg.size.height;
    rect.origin.x = px;
    rect.origin.y = py;
    [fishimg drawInRect:rect];  
    NSTimeInterval timeInterval = [start timeIntervalSinceNow];
    timeInterval  *= 1000;
    NSLog(@"%f",timeInterval);
}

MY Fish is 21x16px , 32 Bit Color, at PNG Format costs 10 ms on to draw on real Device... Very Slow !

p/s : After one day, I found the good solution: Used CGLayerRef and CGContextDrawLayerInRect is 10x - 15x faster than drawInRect. Hope it's useful to you !

Upvotes: 2

Views: 1338

Answers (2)

Mike
Mike

Reputation: 8963

You need to make sure you aren't REdrawing your fish every cycle. drawInRect is not meant to be used (unless absolutely necessary) to redraw your visuals. The idea is that drawInRect is called once and that output is cached for reuse. So say if you have 100 fish, you call drawInRect once for each fish. Further operations (movement, etc) are then just translations on the UIView. E.g., view.frame.origin = CGMakePoint(100, 100), etc. So when the app starts up, you draw 100 fish views and then move them off screen. If the user enters 50, you move 50 fish views on screen. If they enter 100, you move all 100 on screen.

Typically, each fish would be one UIView. They are very efficient.

Upvotes: 1

Erik B
Erik B

Reputation: 42554

Have you tried removing the NSLog?

NSLog is very slow and the timer functionality also consumes time. If you need to measure the time don't do it for every fish, but for all of them.

EDIT: After learning what device you are using I would say that your device is too slow rather than your code.

I'm not sure what the purpose of your app is, but if you enter a number and the app will draw that number of fish, maybe the user finds it acceptable to wait for 1 second. So it might even be fast enough already.

Upvotes: 0

Related Questions