之前無意間看到優(yōu)酷視頻有個GIF截取的功能明棍,感覺相當炫酷排作,于是自己就想著有空搞一個牵啦,前一陣子抽空查資料發(fā)現(xiàn)OC原生的有相關的方法,就整理了下妄痪,然后又忘了分享出來,這不楞件,又看到了衫生,所以這次還是po出來,讓大家看看土浸,相互進步吧罪针。
我叫杜甫,我很忙.png
先把調(diào)用的那行代碼拿出來黄伊,讓大家看的省心點(免得說樓主騙人泪酱,說好的一行代碼,吧嗒吧嗒這么久还最?)
示例--已經(jīng)是錄好的gif
// web就是要錄制gif的view
[screenShotToll RecordScreenInView:web During:5 gifPath:^(NSString *gifsPath) {
// 獲取到gif保存的地址墓阀,可以顯示可以儲存
NSLog(@"%@",gifsPath);
// 顯示
UIWebView *webs = [[UIWebView alloc] init];
webs.frame = CGRectMake(0, sheight / 2,swidth, sheight / 2);
[self.view addSubview:webs];
NSData *gifData = [NSData dataWithContentsOfFile:gifsPath];
[webs loadData:gifData MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
// 儲存
NSData *data = [NSData dataWithContentsOfFile:gifsPath];
// 保存到本地相冊 ALAssetsLibrary需要導入頭文件
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageDataToSavedPhotosAlbum:data metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
NSLog(@"Success at %@", [assetURL path] );
}] ;
}];
首先,乍一聽軟件錄屏(GIF制作)好像特別高大上拓轻,感覺無從下手斯撮,分析開來,gif都是由一幀一幀的圖片組合而成扶叉,經(jīng)過多張圖片的處理最后形成新的文件格式.gif勿锅。那么單張圖片怎么獲取呢?答案很簡單枣氧,原生代碼擼幾行就好了溢十,如下:返回的就是屏幕截圖或者可以是屏幕內(nèi)任意view的截圖
+ (UIImage *)shotInView:(UIView *)view
{
UIGraphicsBeginImageContext(view.bounds.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
接下來就要獲取到錄屏時間內(nèi)的所有截圖用于制作gif
- (void)writeImageToHD:(NSInteger)time inView:(UIView *)view writeOk:(void (^)(BOOL isOK))writeOK
{
// 創(chuàng)建gif圖的文件保存目錄
__block NSString *imagePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
imagePath = [imagePath stringByAppendingPathComponent:@"gif"];
[[screenShotToll shareInstance].manager createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil];
__block int i = 1;
// 為即將保存的圖片設置圖片名稱
__block NSString *imagePS = [imagePath stringByAppendingString:[NSString stringWithFormat:@"/image-%d.png",i]];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:.1 repeats:YES block:^(NSTimer * _Nonnull timer) {
// 將定時器時間內(nèi)每隔.1(截圖頻率,自己可以控制)的屏幕截圖儲存起來达吞,保存成功后進行下一張存放
if ([UIImagePNGRepresentation([screenShotToll shotInView:view]) writeToFile:imagePS atomically:YES] && i < (time / .1)) {
i ++;
imagePS = [imagePath stringByAppendingString:[NSString stringWithFormat:@"/image-%d.png",i]];
}else{
// 屏幕截圖完成后返回YES张弛,圖片數(shù)量 = time / 截圖頻率
[timer invalidate];
timer = nil;
writeOK(YES);
}
}];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
最后就是重頭戲,將上述截圖完成的圖片們組合成一個完整的GIF
+ (void)RecordScreenInView:(UIView *)view During:(NSInteger)time gifPath:(void (^)(NSString *gifsPath))gifsPath
{
[[screenShotToll shareInstance] writeImageToHD:time inView:view writeOk:^(BOOL isOK) {
if (isOK) {
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
path = [path stringByAppendingPathComponent:@"/gif"];
// 創(chuàng)建數(shù)組保存所有圖片
NSMutableArray *images = [NSMutableArray array];
for (int j = 1; j < time / .1; j ++) {
UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/image-%d.png",path,j]];
if (image) {
[images addObject:image];
}
}
CGImageDestinationRef destination;
NSString *doucument = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// 設置gif圖的儲存地址
NSString *gif = [doucument stringByAppendingPathComponent:@"gif"];
[[screenShotToll shareInstance].manager createDirectoryAtPath:gif withIntermediateDirectories:YES attributes:nil error:nil];
// 獲取gif的儲存地址 --- 再往下的是我在網(wǎng)上扒了好久扒到的
NSString *gifPath = [gif stringByAppendingPathComponent:@"image.gif"];
CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)gifPath, kCFURLPOSIXPathStyle, false);
destination = CGImageDestinationCreateWithURL(url,kUTTypeGIF, images.count, NULL);
// 接下來配置制作gif時的一些屬性
NSDictionary *framePro = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:.5],(NSString *)kCGImagePropertyGIFDelayTime, nil] forKey:(NSString *)kCGImagePropertyGIFDictionary];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];
[dict setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCGImagePropertyGIFHasGlobalColorMap];
[dict setObject:[NSNumber numberWithInt:8] forKey:(NSString *)kCGImagePropertyDepth];
[dict setObject:(NSString *)kCGImagePropertyGIFImageColorMap forKey:(NSString *)kCGImagePropertyColorModel];
[dict setObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount];
// 遍歷截圖數(shù)組,制作gif圖
NSDictionary *gifPro = [NSDictionary dictionaryWithObject:dict forKey:(NSString *)kCGImagePropertyGIFDictionary];
for (UIImage *image in images) {
CGImageDestinationAddImage(destination, image.CGImage, (__bridge CFDictionaryRef)framePro);
}
CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)gifPro);
CGImageDestinationFinalize(destination);
CFRelease(destination);
gifsPath(gifPath);
}
}];
}
好了留下demo乌庶,覺得好的可以給星爸值!謝謝大家支持