第一種方法(截全屏幕)
下面這段代碼可以將當(dāng)前屏幕顯示的內(nèi)容截圖放置相冊(cè)中沸毁,需要導(dǎo)入
-(void)viewDidAppear:(BOOL)animated
{
[superviewDidAppear:animated];
self.view.backgroundColor= [UIColorgreenColor];
UIWindow*screenWindow = [[UIApplicationsharedApplication]keyWindow];
UIGraphicsBeginImageContext(screenWindow.frame.size);
[screenWindow.layerrenderInContext:UIGraphicsGetCurrentContext()];
UIImage* viewImage =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage,nil,nil,nil);
}
第二種方法(自定義截圖區(qū)域)
#pragmamark -=====自定義截屏位置大小的邏輯代碼=====-
staticintScreenshotIndex=0; //
-(void)ScreenShot{
//這里因?yàn)槲倚枰两訄D所以直接改了省撑,宏定義iPadWithd為1024,iPadHeight為768,
//UIGraphicsBeginImageContextWithOptions(CGSizeMake(640, 960), YES, 0);//設(shè)置截屏大小
UIGraphicsBeginImageContextWithOptions(CGSizeMake(iPadWidth, iPadHeight), YES,0);//設(shè)置截屏大小
[[self.view layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRef imageRef =viewImage.CGImage;
//CGRect rect = CGRectMake(166, 211, 426, 320);//這里可以設(shè)置想要截圖的區(qū)域
CGRect rect = CGRectMake(0,0, iPadWidth, iPadHeight);//這里可以設(shè)置想要截圖的區(qū)域
CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);
UIImage *sendImage =[[UIImage alloc] initWithCGImage:imageRefRect];
UIImageWriteToSavedPhotosAlbum(sendImage, nil, nil, nil);//保存圖片到照片庫
NSData *imageViewData =UIImagePNGRepresentation(sendImage);
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pictureName= [NSString stringWithFormat:@"screenShow_%d.png",ScreenshotIndex];
NSString *savedImagePath =[documentsDirectory stringByAppendingPathComponent:pictureName];
NSLog(@"截屏路徑打印: %@", savedImagePath);
//這里我將路徑設(shè)置為一個(gè)全局String,這里做的不好掂骏,我自己是為了用而已,希望大家別這么寫
[self SetPickPath:savedImagePath];
[imageViewData writeToFile:savedImagePath atomically:YES];//保存照片到沙盒目錄
CGImageRelease(imageRefRect);
ScreenshotIndex++;
}
//設(shè)置路徑
- (void)SetPickPath:(NSString *)PickImage {
_ScreenshotsPickPath =PickImage;
}
//獲取路徑<這里我就直接用于郵件推送的代碼中去了厚掷,能達(dá)到效果弟灼,但肯定有更好的寫法>
- (NSString *)GetPickPath {
return_ScreenshotsPickPath;
}