How to improve 2D graphics speed?

Discussion in 'iOS Programming' started by pinsrw, Jan 17, 2011.

  1. pinsrw macrumors regular

    May 30, 2010
    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.
  2. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    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.
  3. pinsrw thread starter macrumors regular

    May 30, 2010
    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.
  4. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    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.
  5. firewood macrumors 604

    Jul 29, 2003
    Silicon Valley
    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.
  6. dejo Moderator


    Staff Member

    Sep 2, 2004
    The Centennial State

Share This Page