今天在修改項目bug的時候遇到了,截圖視頻預覽圖的時候總是方向不對,豎屏錄制的視頻(好像是豎屏錄制截圖出的錯,記不太清楚了??)截圖出來總是向左旋轉了90度。
開始我查看圖片的imageOrientation
屬性,發現都是Up
,然后我試著查看圖片的width
和height
,發現無論是對的還是錯的,width
和height
都是一樣,oh,shit!
后來我發現了appliesPreferredTrackTransform
這個屬性,默認是false
(Objective-C中為NO),只要將其設置為true
,在進行截圖就會發現,方向正常了。
截圖代碼如下:
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; // 截圖的時候調整到正確的方向
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];