iOS截图代码

jopen 11年前

屏幕截图小代码,注意设置高宽和截图区域,非ARC下注意释放sendImage。

    //截图   UIGraphicsBeginImageContextWithOptions(CGSizeMake(640, 960), YES, 0);   [self.layer renderInContext:UIGraphicsGetCurrentContext()];   UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();   UIGraphicsEndImageContext();   CGImageRef imageRef = viewImage.CGImage;   CGRect rect =CGRectMake(100, 100, 200, 300);//这里可以设置想要截图的区域   CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);   UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRefRect];   NSData *imageViewData = UIImagePNGRepresentation(sendImage);      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);   NSString *documentsDirectory = [paths objectAtIndex:0];   NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"result.png"];      NSLog(@"%@", savedImagePath);   [imageViewData writeToFile:savedImagePath atomically:YES];   CGImageRelease(imageRefRect);