Breaking News
Home / iOS / iOS Snippets / How to take screenshot in iOS using Code?

How to take screenshot in iOS using Code?

Ios Framework WeaklinkTaking screenshot of the an application view/screen from the app itself involves the use of GL API which is part of QuartzCore Framework as show below:

<!>Code

#import <QuartzCore/QuartzCore.h>

 
 
(UIImage*)captureView:(UIView *)view

{
CGRect rect = [[UIScreen mainScreen] bounds];

UIGraphicsBeginImageContext(rect.size);

CGContextRef context = UIGraphicsGetCurrentContext();

[view.layer renderInContext:context];

UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
 

return img;

}
 
(void)saveScreenshotToPhotosAlbum:(UIView *)view

{
UIImageWriteToSavedPhotosAlbum([self captureView:view], nil, nil, nil);

}

- (UIImage*) getGLScreenshot {
    NSInteger myDataLength = 320 * 480 * 4;
 
    // allocate array and read pixels into it.
    GLubyte *buffer = (GLubyte *) malloc(myDataLength);
    glReadPixels(0, 0, 320, 480, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
 
    // gl renders "upside down" so swap top to bottom into new array.
    // there's gotta be a better way, but this works.
    GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
    for(int y = 0; y <480; y++)
    {
        for(int x = 0; x <320 * 4; x++)
        {
            buffer2[(479 - y) * 320 * 4 + x] = buffer[y * 4 * 320 + x];
        }
    }
 
    // make data provider with data.
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL,
 buffer2, myDataLength, NULL);   // prep the ingredients int bitsPerComponent = 8; int bitsPerPixel = 32; int bytesPerRow = 4 * 320; CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault; CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;   // make the cgimage CGImageRef imageRef = CGImageCreate(320, 480, bitsPerComponent,
bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider,
 NULL, NO, renderingIntent);   // then make the uiimage from that UIImage *myImage = [UIImage imageWithCGImage:imageRef]; return myImage; }   - (void)saveGLScreenshotToPhotosAlbum { UIImageWriteToSavedPhotosAlbum([self getGLScreenshot], nil,
 nil, nil); }
[pb_builder]

Check Also

EKCalendar – That account does not allow calendars to be added or removed

Usecase When I am trying to create a new Calendar programmatically using the EventKit API …

Leave a Reply