ios截屏代碼[轉]

這位博主的鏈接中將ios自定義大小位置的截屏代碼寫的很不錯,立刻就能用的方法,對於只想立刻用的程序員頗有幫助html

http://www.2cto.com/kf/201310/250228.htmlios

 

我將其改成如下代碼:程序員

 1 #pragma mark -=====自定義截屏位置大小的邏輯代碼=====-
 2 static int ScreenshotIndex=0; //這裏的邏輯直接採用上面博主的邏輯了
 3 -(void)ScreenShot{
 4     //這裏由於我須要全屏接圖因此直接改了,宏定義iPadWithd爲1024,iPadHeight爲768,
 5 //    UIGraphicsBeginImageContextWithOptions(CGSizeMake(640, 960), YES, 0);     //設置截屏大小
 6     UIGraphicsBeginImageContextWithOptions(CGSizeMake(iPadWidth, iPadHeight), YES, 0);     //設置截屏大小
 7     [[self.view layer] renderInContext:UIGraphicsGetCurrentContext()];
 8     UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
 9     UIGraphicsEndImageContext();
10     CGImageRef imageRef = viewImage.CGImage;
11 //    CGRect rect = CGRectMake(166, 211, 426, 320);//這裏能夠設置想要截圖的區域
12     CGRect rect = CGRectMake(0, 0, iPadWidth, iPadHeight);//這裏能夠設置想要截圖的區域
13     CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);
14     UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRefRect];
15     UIImageWriteToSavedPhotosAlbum(sendImage, nil, nil, nil);//保存圖片到照片庫
16     NSData *imageViewData = UIImagePNGRepresentation(sendImage);
17     
18     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
19     NSString *documentsDirectory = [paths objectAtIndex:0];
20     NSString *pictureName= [NSString stringWithFormat:@"screenShow_%d.png",ScreenshotIndex];
21     NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:pictureName];
22     NSLog(@"截屏路徑打印: %@", savedImagePath);
23     //這裏我將路徑設置爲一個全局String,這裏作的很差,我本身是爲了用而已,但願你們別這麼寫
24     [self SetPickPath:savedImagePath];
25 
26     [imageViewData writeToFile:savedImagePath atomically:YES];//保存照片到沙盒目錄
27     CGImageRelease(imageRefRect);
28     ScreenshotIndex++;
29 }
30 //設置路徑
31 - (void)SetPickPath:(NSString *)PickImage {
32     _ScreenshotsPickPath = PickImage;
33 }
34 //獲取路徑<這裏我就直接用於郵件推送的代碼中去了,能達到效果,但確定有更好的寫法>
35 - (NSString *)GetPickPath {
36     return _ScreenshotsPickPath;
37 }

 重要備註: 上面代碼只適用於截取普通視圖如:UIScrollView、UIView、UIImageView等等,不適用於OpenGL ES、相機內容等,若須要實現對三維模型或者拍照一類截屏功能,還須要另外尋找截取OpenGL渲染區部分的截屏代碼或者截取相機內容的截屏代碼。atom

相關文章
相關標籤/搜索