在OpenGL的環境下把畫面存圖片 Code Snippet
在glpaint裡要把畫面存成照片需要加入以下的程式碼。
void ProviderReleaseData ( void *info, const void *data, size_t size ) {
free((void*)data);
}
-(UIImage*) upsideDownImageRepresenation{
int imageWidth = CGRectGetWidth([self bounds]);
int imageHeight = CGRectGetHeight([self bounds]);
//image buffer for export
NSInteger myDataLength = imageWidth* imageHeight * 4;
// allocate array and read pixels into it.
GLubyte *tempImagebuffer = (GLubyte *) malloc(myDataLength);
glReadPixels(0, 0, imageWidth, imageHeight, GL_RGBA, GL_UNSIGNED_BYTE, tempImagebuffer);
// make data provider with data.
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, tempImagebuffer, myDataLength, ProviderReleaseData);
// prep the ingredients
int bitsPerComponent = 8;
int bitsPerPixel = 32;
int bytesPerRow = 4 * imageWidth;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
// make the cgimage
CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
// then make the uiimage from that
UIImage *myImage = [UIImage imageWithCGImage:imageRef] ;
CGDataProviderRelease(provider);
CGImageRelease(imageRef);
CGColorSpaceRelease(colorSpaceRef);
//make sure it is in the autorelease pool
[[myImage retain] autorelease];
return myImage;
}
-(UIImage*) imageRepresentation{
UIImageView* upsideDownImageView=[[UIImageView alloc] initWithImage: [self upsideDownImageRepresenation]];
upsideDownImageView.transform=CGAffineTransformScale(upsideDownImageView.transform, 1, -1);
UIView* container=[[UIView alloc] initWithFrame:upsideDownImageView.frame];
[container addSubview:upsideDownImageView];
UIImage* toReturn=nil;
UIGraphicsBeginImageContext(container.frame.size);
[container.layer renderInContext:UIGraphicsGetCurrentContext()];
toReturn = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[upsideDownImageView release];
[container release];
return toReturn;
}
設定存檔按鈕
-(void) saveImage{
UIImageWriteToSavedPhotosAlbum([drawingView imageRepresentation], self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
留言
張貼留言