- 按屏幕截圖,即全屏截圖
- (void)doScreenShot{
// 開啟圖片上下文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0);
// 獲取當前上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 截圖:實際是把layer上面的東西繪制到上下文中
[self.view.layer renderInContext:ctx];
//iOS7+ 推薦使用的方法,代替上述方法
// [self.view drawViewHierarchyInRect:self.view.frame afterScreenUpdates:YES];
// 獲取截圖
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 關(guān)閉圖片上下文
UIGraphicsEndImageContext();
// 保存相冊
UIImageWriteToSavedPhotosAlbum(image, NULL, NULL, NULL);
}
- 按內(nèi)容截屏,即截全圖
- (void)screenShots{
UICollectionView *shadowView = self.collectionView;
// 開啟圖片上下文
UIGraphicsBeginImageContextWithOptions(shadowView.contentSize, NO, 0.f);
// 保存現(xiàn)在視圖的位置偏移信息
CGPoint saveContentOffset = shadowView.contentOffset;
// 保存現(xiàn)在視圖的frame信息
CGRect saveFrame = shadowView.frame;
// 把要截圖的視圖偏移量設(shè)置為0
shadowView.contentOffset = CGPointZero;
// 設(shè)置要截圖的視圖的frame為內(nèi)容尺寸大小
shadowView.frame = CGRectMake(0, 0, shadowView.contentSize.width, shadowView.contentSize.height);
// 獲取當前上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 截圖:實際是把layer上面的東西繪制到上下文中
[shadowView.layer renderInContext:ctx];
//iOS7+ 推薦使用的方法,代替上述方法
// [shadowView drawViewHierarchyInRect:shadowView.frame afterScreenUpdates:YES];
// 獲取截圖
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 關(guān)閉圖片上下文
UIGraphicsEndImageContext();
// 將視圖的偏移量設(shè)置回原來的狀態(tài)
shadowView.contentOffset = saveContentOffset;
// 將視圖的frame信息設(shè)置回原來的狀態(tài)
shadowView.frame = saveFrame;
// 保存相冊
UIImageWriteToSavedPhotosAlbum(image, NULL, NULL, NULL);
}
- 視頻截圖
// 需要導入AVFoundation頭文件
#import <AVFoundation/AVFoundation.h>
// videoURL 視頻的URL地址;frameTime 要截取的視頻圖片幀數(shù)
+ (UIImage *)imageWithVideo:(NSURL *)videoURL withVideoCaptureFrame:(NSInteger)frameTime{
// 根據(jù)視頻的URL創(chuàng)建AVURLAsset
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
// 根據(jù)AVURLAsset創(chuàng)建AVAssetImageGenerator對象
AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
gen.appliesPreferredTrackTransform = YES;
// 定義獲取第幾幀處的視頻截圖
// CMTime halfSecond = CMTimeMake(1, 2); //0.5秒
CMTime time = CMTimeMake(frameTime, 10);
CMTime actualTime;
NSError *error = nil;
// 嘗試獲取time處的視頻截圖(實際截屏的時間點保存在actualTime變量中)
CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
if (error == nil) {
// 將CGImageRef轉(zhuǎn)換為UIImage
UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
CGImageRelease(image);
return thumb;
}else{
NSLog(@"對視頻截圖時出現(xiàn)錯誤: %@", error);
return nil;
}
}
附:我的博客地址
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。