iOS開發日記19-7.0之後的截屏方法,ios日記19-7.0截屏
今天博主有一個截屏的需求,遇到了一些困痛點,在此和大家分享,希望能夠共同進步.
iOS7.0之後廢除了之前常用的截屏方法,也新增了截屏的API.代碼相對簡單,今天就貼出來,大家自行研究.
1.
-(void) screenShot
{
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image= UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSLog(@"image:%@",image);
UIImageView *imaView = [[UIImageView alloc] initWithImage:image];
imaView.frame = CGRectMake(0, 0, 100, 100);
[self.view addSubview:imaView];
UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
}
2.
-(void)srceedShot2
{
//延遲兩秒儲存
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//擷取圖形上下文
// UIGraphicsBeginImageContext(self.view.frame.size);
UIGraphicsBeginImageContext(self.view.frame.size);
//將view繪製到圖形上下文中
// [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
//將截屏儲存到相簿
UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
UIImageWriteToSavedPhotosAlbum(newImage,self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
});}
//儲存至相簿後的回調
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
NSString *msg =nil ;
if(error){
msg = @"儲存圖片失敗" ;
}else{
msg = @"儲存圖片成功" ;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"儲存圖片結果提示"
message:msg
delegate:self
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
[alert show];
}
3.
-(void)screenShot3
{
CGSize size = self.view.bounds.size;
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
CGRect rec = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.bounds.size.width, self.view.bounds.size.height);
[self.view drawViewHierarchyInRect:rec afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(image);
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
NSString *filename = [path stringByAppendingPathComponent:@"foo.png"];
[data writeToFile:filename atomically:YES];
NSLog(@"***********%@",filename);
}