Best way to update a bitmap

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

  1. adrian.oconnor macrumors 6502

    Joined:
    Jan 16, 2008
    Location:
    Nottingham, England
    #1
    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:

    Code:
    UIImage* imageByDrawingDotOnImageAtPoint(UIImage* image, int x, int y)
    {
    	// begin a graphics context
    	UIGraphicsBeginImageContext(image.size);
        
    	// 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
    	UIGraphicsEndImageContext();
        
    	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 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #2
    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

    Joined:
    Jan 16, 2008
    Location:
    Nottingham, England
    #3
    Thanks very much for the pointer, I'll go through the guide.
     

Share This Page