Best way to update a bitmap

Discussion in 'iOS Programming' started by adrian.oconnor, Dec 31, 2011.

  1. adrian.oconnor macrumors 6502

    Jan 16, 2008
    Nottingham, England
    Hello programmers. I'm trying to create a basic drawing app that follows touches and draws suitable lines. The app itself isn't important -- really it's just a prototype while I try and find out how I can update a bitmap without having to create a copy every time.

    Currently, when I want to draw on an image, I do this:

    UIImage* imageByDrawingDotOnImageAtPoint(UIImage* image, int x, int y)
    	// begin a graphics context
    	// draw the original image into the context
    	[image drawAtPoint:CGPointZero];
    	// get the context for CoreGraphics
    	CGContextRef ctx = UIGraphicsGetCurrentContext();
    	[[UIColor redColor] setStroke];
            [[UIColor redColor] setFill];
    	CGRect circleRect = CGRectMake(x, y, 10, 10);
    	circleRect = CGRectInset(circleRect, 5, 5);
    	// draw circle
    	CGContextStrokeEllipseInRect(ctx, circleRect);
    	// make image out of bitmap context
    	UIImage *retImage = UIGraphicsGetImageFromCurrentImageContext();
    	// free the context
    	return retImage;
    As you can see, the first thing I do is create an image context based on the size of the existing image, then I copy the old image in to the new image, then I use the context to do the drawing.

    I guess what I want to do is keep hold of the context -- is that possible? Is my variable ctx in the example above always tied to the same image, or does it change based on the context changes that get invoked elsewhere?

    I know I can go and try that out (and I will), but I'd like some feedback if there's anybody here who knows better. Certainly creating a copy of the entire image for each frame seems needlessly wasteful.

    Thanks for any input.
  2. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    Start by reading Apple's Quartz 2D guide.

    UIGraphicsBeginImageContext() is a convenience function that wraps CGBitmapContextCreate(). Most likely you'll need to use that for your purposes.
  3. adrian.oconnor thread starter macrumors 6502

    Jan 16, 2008
    Nottingham, England
    Thanks very much for the pointer, I'll go through the guide.

Share This Page