Http://www.gotow.net/creative/wordpress? P = 33
CGLayers are great for drawing-especially when things need to be drawn over and over again. converting a CGLayer to a UIImage is another story, though. netSketch uses CGLayers for the drawing canvas, but converts them to UIImages when you go to upload your drawing or email it to a friend. the code below shows how it's done. the CGLayer is drawn into a bitmap CGContext of the same size, and then CGImage is created around the CGContext. The CGImage can be turned into a UIImage, and you're done!
Be sure to leave a comment if you find this function useful!
- UIImage * UIImageFromLayer (CGLayerRef layer)
- {
- // Create the bitmap context
- CGContextRef bitmapContext = NULL;
- Void * bitmapData;
- Int bitmapByteCount;
- Int bitmapBytesPerRow;
- CGSize size = CGLayerGetSize (layer );
- // Declare the number of bytes per row. Each pixel in the bitmap in this
- // Example is represented by 4 bytes; 8 bits each of red, green, blue, and
- // Alpha.
- BitmapBytesPerRow = (size. width * 4 );
- BitmapByteCount = (bitmapBytesPerRow * size. height );
- // Allocate memory for image data. This is the destination in memory
- // Where any drawing to the bitmap context will be rendered.
- BitmapData = malloc (bitmapByteCount );
- If (bitmapData = NULL)
- {
- Return nil;
- }
- // Create the bitmap context. We want pre-multiplied ARGB, 8-bits
- // Per component. Regardless of what the source image format is
- // (CMYK, Grayscale, and so on) it will be converted over to the format
- // Specified here by CGBitmapContextCreate.
- BitmapContext = CGBitmapContextCreate (bitmapData, size. width, size. height, 8, bitmapBytesPerRow,
- CGColorSpaceCreateDeviceRGB (), kCGImageAlphaNoneSkipFirst );
- If (bitmapContext = NULL)
- // Error creating context
- Return nil;
- CGContextScaleCTM (bitmapContext, 1,-1 );
- CGContextTranslateCTM (bitmapContext, 0,-size. height );
- // Draw the image to the bitmap context. Once we draw, the memory
- // Allocated for the context for rendering will then contain
- // Raw image data in the specified color space.
- CGContextDrawLayerAtPoint (bitmapContext, CGPointZero, layer );
- CGImageRef img = CGBitmapContextCreateImage (bitmapContext );
- UIImage * ui_img = [UIImage imageWithCGImage: img];
- CGImageRelease (img );
- CGContextRelease (bitmapContext );
- Free (bitmapData );
- Return ui_img;
- }
In general, CGLayer is painted on the newly created CGContext and then converted to UIImage. My method will be simpler.
UIImage * UIImageFromLayer (CGLayerRef layer) <br/>{< br/> CGContextRef ctx = CGLayerGetContext (layer); <br/> CGImageRef img = CGBitmapContextCreateImage (bitmapContext ); <br/> UIImage * ui_img = [UIImage imageWithCGImage: img]; <br/>}