PDA

View Full Version : How to improve 2D graphics speed?




pinsrw
Jan 17, 2011, 07:22 AM
Hi all,

I am attempting to draw in the touchesMoved method. As yet the only way I know to draw (I'm a beginner) is to:

1. create a context using UIGraphicsBeginImageContext.
2. send the UIImage if the UIImageView the message drawInRect, providing a rectangle of the entire image.
3. fetch the context using UIGraphicsGetCurrentContext.
4. do my drawing in the context using CGContextBeginPath, CGContextMoveToPoint, CGContextAddLineToPoint and CGContextStrokePath.
5. store the image into the UIImageView using UIGraphicsGetImageFromCurrentImageContext.

However this is taking too much time. What is the faster way to draw?

FYI normally on any other system what I'd do is clip my drawing area to just the rectangle I'm affecting, and clip the blit from image to screen. However when I attempt to clip the drawing region with drawInRect, this ends up -clearing- the area outside of that rectangle in the UIImage. There must be a way to speed this up...

Thank you.



PhoneyDeveloper
Jan 17, 2011, 11:11 AM
That's not how drawing is supposed to work.

The normal way to draw in response to a touch is to change the state of your view and then call setNeedsDisplay on the view (or better the view calls it on itself). No images or temporary contexts are required.

pinsrw
Jan 21, 2011, 07:38 PM
That's not how drawing is supposed to work.

The normal way to draw in response to a touch is to change the state of your view and then call setNeedsDisplay on the view (or better the view calls it on itself). No images or temporary contexts are required.

Can you clarify? All the examples I've found work exactly like I described. Also, when I tried using setNeedsDisplay instead of writing the image back into the UIImageView it had no effect at all.
Thanks.

PhoneyDeveloper
Jan 22, 2011, 12:12 AM
Consider that you have a view that is like a label, or like a button. In it's drawrect it draws a line of text, which is an ivar. It sets the text to "Not Touched" when it's inited. When it's touched it sets the text to "Touched" and calls setNeedsDisplay. In drawRect it just draws the text stored in the ivar. When the touch ends the ivar is set to "Not Touched" and it calls setNeedsDisplay. Shortly after that it draws the value of the ivar.

That's how drawing is supposed to work.

firewood
Jan 22, 2011, 02:13 PM
2D graphic drawing is not accelerated on current iPhone devices.

Your options are:

Don't redraw. Only draw the latest updates and overlay them over old content. e.g. Don't draw 100 line segments, just the latest one onto a small overlay layer. Maybe composite layers lazily in a background thread.

Set pixels in a bitmap and upload to a CALayer at some animation frame rate.

Use OpenGL. Make your lines into polygons. 3D drawing can be GPU accelerated.

dejo
Jan 22, 2011, 02:22 PM
Perhaps look into using a framework like cocos2d for iPhone (http://www.cocos2d-iphone.org/).