今天在修改項(xiàng)目bug的時(shí)候遇到了,截圖視頻預(yù)覽圖的時(shí)候總是方向不對(duì),豎屏錄制的視頻(好像是豎屏錄制截圖出的錯(cuò),記不太清楚了??)截圖出來(lái)總是向左旋轉(zhuǎn)了90度。
開(kāi)始我查看圖片的imageOrientation屬性,發(fā)現(xiàn)都是Up,然后我試著查看圖片的width和height,發(fā)現(xiàn)無(wú)論是對(duì)的還是錯(cuò)的,width和height都是一樣,oh,shit!
后來(lái)我發(fā)現(xiàn)了appliesPreferredTrackTransform這個(gè)屬性,默認(rèn)是false(Objective-C中為NO),只要將其設(shè)置為true,在進(jìn)行截圖就會(huì)發(fā)現(xiàn),方向正常了。
截圖代碼如下:
NSURL *url = [[NSURL alloc] initWithString:@"Your video url"];
AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:urlAsset];
imageGenerator.appliesPreferredTrackTransform = YES; // 截圖的時(shí)候調(diào)整到正確的方向
CMTime time = CMTimeMakeWithSeconds(1.0, 30); // 1.0為截取視頻1.0秒處的圖片,30為每秒30幀
CGImageRef cgImage = [imageGenerator copyCGImageAtTime:time actualTime:nil error:nil];
UIImage *image = [UIImage imageWithCGImage:cgImage];