2015-04-04 14 views
5

Ecco il link su github https://github.com/spennyf/cropVid/tree/master per provarlo e vedere cosa sto parlando ci vorrebbe 1 minuto per testare. Grazie!L'area di ritaglio è diversa dall'area selezionata in iOS?

Sto scattando un video con un quadrato per mostrare quale parte del video verrà ritagliata. Come questo:

enter image description here

In questo momento sto facendo questo di un pezzo di carta con 4 linee in piazza, e per metà una differenza sulla linea superiore e inferiore. E poi ho ritagliare il video utilizzando il codice mi post, ma poi quando ho visualizzare il video vedo questo (Ignora sfondo e cerchio verde):

enter image description here

Come potete vedere ci sono più di quattro linee, quindi lo sto impostando per ritagliare una certa parte ma ne aggiungo di più, quando sto usando lo stesso rettangolo che viene visualizzato nella fotocamera e lo stesso rettangolo che viene usato per ritagliare?

Quindi la mia domanda è: perché il ritaglio non è della stessa dimensione?

Ecco come faccio delle colture e di visualizzazione:

//this is the square on the camera 
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-80)]; 
    UIImageView *image = [[UIImageView alloc] init]; 
    image.layer.borderColor=[[UIColor whiteColor] CGColor]; 
image.frame = CGRectMake(self.view.frame.size.width/2 - 58 , 100 , 116, 116); 
    CALayer *imageLayer = image.layer; 
    [imageLayer setBorderWidth:1]; 
[view addSubview:image]; 
    [picker setCameraOverlayView:view]; 

//this is crop rect 
CGRect rect = CGRectMake(self.view.frame.size.width/2 - 58, 100, 116, 116); 
[self applyCropToVideoWithAsset:assest AtRect:rect OnTimeRange:CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(assest.duration.value, 1)) 
        ExportToUrl:exportUrl ExistingExportSession:exporter WithCompletion:^(BOOL success, NSError *error, NSURL *videoUrl) { 
//here is player 
AVPlayer *player = [AVPlayer playerWithURL:videoUrl]; 

          AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:player]; 
layer.frame = CGRectMake(self.view.frame.size.width/2 - 58, 100, 116, 116); 
}]; 

E qui è il codice che fa il raccolto:

- (UIImageOrientation)getVideoOrientationFromAsset:(AVAsset *)asset 
{ 
    AVAssetTrack *videoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]; 
CGSize size = [videoTrack naturalSize]; 
CGAffineTransform txf = [videoTrack preferredTransform]; 

if (size.width == txf.tx && size.height == txf.ty) 
    return UIImageOrientationLeft; //return UIInterfaceOrientationLandscapeLeft; 
else if (txf.tx == 0 && txf.ty == 0) 
    return UIImageOrientationRight; //return UIInterfaceOrientationLandscapeRight; 
else if (txf.tx == 0 && txf.ty == size.width) 
    return UIImageOrientationDown; //return UIInterfaceOrientationPortraitUpsideDown; 
else 
    return UIImageOrientationUp; //return UIInterfaceOrientationPortrait; 
} 

Ed ecco resto del codice ritaglio:

- (AVAssetExportSession*)applyCropToVideoWithAsset:(AVAsset*)asset AtRect:(CGRect)cropRect OnTimeRange:(CMTimeRange)cropTimeRange ExportToUrl:(NSURL*)outputUrl ExistingExportSession:(AVAssetExportSession*)exporter WithCompletion:(void(^)(BOOL success, NSError* error, NSURL* videoUrl))completion 
{ 

// NSLog(@"CALLED"); 
//create an avassetrack with our asset 
AVAssetTrack *clipVideoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]; 

//create a video composition and preset some settings 
AVMutableVideoComposition* videoComposition = [AVMutableVideoComposition videoComposition]; 
videoComposition.frameDuration = CMTimeMake(1, 30); 

CGFloat cropOffX = cropRect.origin.x; 
CGFloat cropOffY = cropRect.origin.y; 
CGFloat cropWidth = cropRect.size.width; 
CGFloat cropHeight = cropRect.size.height; 
// NSLog(@"width: %f - height: %f - x: %f - y: %f", cropWidth, cropHeight, cropOffX, cropOffY); 

videoComposition.renderSize = CGSizeMake(cropWidth, cropHeight); 

//create a video instruction 
AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction]; 
instruction.timeRange = cropTimeRange; 

AVMutableVideoCompositionLayerInstruction* transformer = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:clipVideoTrack]; 

UIImageOrientation videoOrientation = [self getVideoOrientationFromAsset:asset]; 

CGAffineTransform t1 = CGAffineTransformIdentity; 
CGAffineTransform t2 = CGAffineTransformIdentity; 

switch (videoOrientation) { 
    case UIImageOrientationUp: 
     t1 = CGAffineTransformMakeTranslation(clipVideoTrack.naturalSize.height - cropOffX, 0 - cropOffY); 
     t2 = CGAffineTransformRotate(t1, M_PI_2); 
     break; 
    case UIImageOrientationDown: 
     t1 = CGAffineTransformMakeTranslation(0 - cropOffX, clipVideoTrack.naturalSize.width - cropOffY); // not fixed width is the real height in upside down 
     t2 = CGAffineTransformRotate(t1, - M_PI_2); 
     break; 
    case UIImageOrientationRight: 
     t1 = CGAffineTransformMakeTranslation(0 - cropOffX, 0 - cropOffY); 
     t2 = CGAffineTransformRotate(t1, 0); 
     break; 
    case UIImageOrientationLeft: 
     t1 = CGAffineTransformMakeTranslation(clipVideoTrack.naturalSize.width - cropOffX, clipVideoTrack.naturalSize.height - cropOffY); 
     t2 = CGAffineTransformRotate(t1, M_PI ); 
     break; 
    default: 
     NSLog(@"no supported orientation has been found in this video"); 
     break; 
} 

CGAffineTransform finalTransform = t2; 
[transformer setTransform:finalTransform atTime:kCMTimeZero]; 

//add the transformer layer instructions, then add to video composition 
instruction.layerInstructions = [NSArray arrayWithObject:transformer]; 
videoComposition.instructions = [NSArray arrayWithObject: instruction]; 

//Remove any prevouis videos at that path 
[[NSFileManager defaultManager] removeItemAtURL:outputUrl error:nil]; 

if (!exporter){ 
    exporter = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality] ; 
} 
// assign all instruction for the video processing (in this case the transformation for cropping the video 
exporter.videoComposition = videoComposition; 
exporter.outputFileType = AVFileTypeQuickTimeMovie; 
if (outputUrl){ 
    exporter.outputURL = outputUrl; 
    [exporter exportAsynchronouslyWithCompletionHandler:^{ 
     switch ([exporter status]) { 
      case AVAssetExportSessionStatusFailed: 
       NSLog(@"crop Export failed: %@", [[exporter error] localizedDescription]); 
       if (completion){ 
        dispatch_async(dispatch_get_main_queue(), ^{ 
         completion(NO,[exporter error],nil); 
        }); 
        return; 
       } 
       break; 
      case AVAssetExportSessionStatusCancelled: 
       NSLog(@"crop Export canceled"); 
       if (completion){ 
        dispatch_async(dispatch_get_main_queue(), ^{ 
         completion(NO,nil,nil); 
        }); 
        return; 
       } 
       break; 
      default: 
       break; 
     } 
     if (completion){ 
      dispatch_async(dispatch_get_main_queue(), ^{ 
       completion(YES,nil,outputUrl); 
      }); 
     } 

    }]; 
} 

return exporter; 
} 

Quindi la mia domanda è: perché l'area video non è uguale all'area di ritaglio/fotocamera, quando ho usato esattamente le stesse coordinate ize of square?

+0

Per sicurezza, una volta eseguito il video ritagliato (quindi nel blocco di completamento), è necessario salvarlo sul disco dell'iPhone. Per favore, controlla quel file direttamente, intendo l'accesso al file (collegando l'iphone al mac e usando strumenti come iExplorer o iFunBox). quindi copialo sul mac e aprilo con il player mac quick time predefinito. In questo modo sarai sicuro che il video ritagliato risultante è esattamente quello che vedi in quella casella. Inoltre, assicurati che l'area di ritaglio utilizzi le coordinate corrette per la vista di riferimento, per entrambi gli assi x e –

+0

@LucaIaco. Ok, sto usando iExplorer e metto il video sul mio Mac e l'ho riprodotto con tempo veloce e l'area ritagliata è ancora Non corretto. Ho guardato le coordinate ancora e ancora e sono sicuro che abbiano ragione. Ho intenzione di fare un progetto di hub git a postare il link, in modo da poter scaricare ed eseguire e vedere di persona se non ti dispiacerebbe. In questo momento sto prendendo il video di un quadrato verde e solo il quadrato nella parte ritagliata, ma poi vedo bianco quando è tagliato. Apprezzerei molto se guardi al progetto – iqueqiorio

+0

Ecco il link corretto https://github.com/spennyf/cropVid – iqueqiorio

risposta

-2

Forse Check This Previous Question.

Sembra che potrebbe essere simile a quello che stai vivendo. Un utente su tale questione ha suggerito di ritaglio in questo modo:

CGImageRef imageRef = CGImageCreateWithImageInRect([originalImage CGImage], cropRect); 
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef]; 
CGImageRelease(imageRef); 

Spero che questo aiuta o almeno ti dà un inizio nella giusta direzione.

+0

Questa risposta è completamente irrilevante. La domanda chiede di ritagliare un video, non un'immagine. – bgfriend0

+0

Scusaci, sono stato sveglio fino a tardi e ho letto male questo! Grazie per il testa a testa. – Kleigh

+0

Haha, np, succede a tutti noi. – bgfriend0