1. 程式人生 > >iOS 截圖的實現

iOS 截圖的實現

一.普通截圖

-(UIImage *)convertViewToImage:(UIView*)v{
    CGSize s = v.bounds.size;
    // 下面方法,第一個引數表示區域大小。第二個引數表示是否是非透明的。如果需要顯示半透明效果,需要傳NO,否則傳YES。第三個引數就是螢幕密度了,調整清晰度。
    UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
    [v.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage
*image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }

二.長截圖


// 長截圖 型別可以是 tableView或者scrollView 等可以滾動的檢視 根據需要自己改
- (UIImage *)saveLongImage:(UIScrollView *)table {
    UIImage* image = nil;
    // 下面方法,第一個引數表示區域大小。第二個引數表示是否是非透明的。如果需要顯示半透明效果,需要傳NO,否則傳YES。第三個引數就是螢幕密度了,調整清晰度。
UIGraphicsBeginImageContextWithOptions(table.contentSize, YES, [UIScreenmainScreen].scale); CGPoint savedContentOffset = table.contentOffset; CGRect savedFrame = table.frame; table.contentOffset = CGPointZero; table.frame = CGRectMake(0, 0, table.contentSize.width, table.contentSize
.height); [table.layerrenderInContext: UIGraphicsGetCurrentContext()]; image = UIGraphicsGetImageFromCurrentImageContext(); table.contentOffset = savedContentOffset; table.frame = savedFrame; UIGraphicsEndImageContext(); if (image != nil) { //儲存圖片到相簿 UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL); } return image; } // 儲存後回撥方法 - (void)image: (UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo { NSString *msg = nil ; if(error != NULL){ msg = @"儲存圖片失敗" ; }else{ msg = @"儲存圖片成功,可到相簿檢視" ; } UIAlertView *alert = [[UIAlertViewalloc] initWithTitle:nilmessage:msg delegate:selfcancelButtonTitle:@"確定" otherButtonTitles:nil]; [alert show]; }