Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing Screen

I am trying to capture (screen shot) a view. For that I am using a piece of code shown below that saves it to my document directory as a PNG image.

UIGraphicsBeginImageContextWithOptions(highlightViewController.fhView.centerView.frame.size, YES, 1.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"1.png"];
NSData *imageData = UIImagePNGRepresentation(screenshot);
[imageData writeToFile:appFile atomically:YES];
UIGraphicsEndImageContext();

Question: can I capture part of the view? Because in the above code I can't change the origin (frame). If anyone has other approach to capture a particular part of view please share it.

like image 240
ajay Avatar asked Sep 15 '11 11:09

ajay


2 Answers

You could crop the image: http://iosdevelopertips.com/graphics/how-to-crop-an-image.html

CGRect rect = CGRectMake(0,0,10,10);
CGImageRef imageRef = CGImageCreateWithImageInRect([screenshot CGImage], rect);
UIImage *croppedScreenshot = [UIImage imageWithCGImage:imageRef]; 
CGImageRelease(imageRef);
like image 150
Lenar Hoyt Avatar answered Sep 28 '22 06:09

Lenar Hoyt


Try this code. This surely works as I have implemented it in many of my projects:

- (UIImage *)image
{
    if (cachedImage == nil) {
        //YOU CAN CHANGE THE FRAME HERE TO WHATEVER YOU WANT TO CAPTURE
        CGRect imageFrame = CGRectMake(0, 0, 400, 300); 
        UIView *imageView = [[UIView alloc] initWithFrame:imageFrame];
        [imageView setOpaque:YES];
        [imageView setUserInteractionEnabled:NO];

        [self renderInView:imageView withTheme:nil];        

        UIGraphicsBeginImageContext(imageView.bounds.size);
            CGContextRef c = UIGraphicsGetCurrentContext();
            CGContextGetCTM(c);
            CGContextScaleCTM(c, 1, -1);
            CGContextTranslateCTM(c, 0, -imageView.bounds.size.height);
            [imageView.layer renderInContext:c];
            cachedImage = [UIGraphicsGetImageFromCurrentImageContext() retain];

            // rescale graph
            UIImage* bigImage = UIGraphicsGetImageFromCurrentImageContext();
            CGImageRef scaledImage = [self newCGImageFromImage:[bigImage CGImage] scaledToSize:CGSizeMake(100.0f, 75.0f)];
            cachedImage = [[UIImage imageWithCGImage:scaledImage] retain];
            CGImageRelease(scaledImage);
        UIGraphicsEndImageContext();

        [imageView release];
    }

    return cachedImage;
}

I hope this will help you.

like image 22
Parth Bhatt Avatar answered Sep 28 '22 06:09

Parth Bhatt