2016-03-10 61 views
2

我有在蘋果的文檔提出創建AVPlayerView: https://developer.apple.com/library/ios/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/02_Playback.html如何使AVPlayer與父視圖一起調整大小?

所以我補充一點,UIView子類作爲我的UIViewController子視圖。

它看起來不錯,視頻播放很好。 但是,當我將視圖最小化爲一個小窗口時,視頻不會隨其調整大小。 沒問題,當我使用MPMoviePlayerViewController時,但我有一個需要使用AVPlayer的原因很少[靜音音頻,同時播放多個視頻等]。

這裏是我的AVPlayerView實現:

@implementation VideoView { 

} 

+ (Class)layerClass { 
    return [AVPlayerLayer class]; 
} 

- (AVPlayer*)player { 
    return [(AVPlayerLayer *)[self layer] player]; 
} 

- (void)setPlayer:(AVPlayer *)player { 
    [(AVPlayerLayer *)[self layer] setPlayer:player]; 
} 

@end 

下面是如何創建AVPlayer:

AVAsset *asset = [AVURLAsset URLAssetWithURL:Url options:nil]; 
    AVPlayerItem *anItem = [AVPlayerItem playerItemWithAsset:asset]; 
    player_vc = [AVPlayer playerWithPlayerItem:anItem]; 
    player_vc.actionAtItemEnd = AVPlayerActionAtItemEndNone; 

    player_layer = [[VideoView alloc] initWithFrame:self.view.bounds]; 
    [self.view addSubview: player_layer]; 

    [player_layer setPlayer:player_vc]; 

下面是我用更改父視圖的框架代碼:

-(void) minimize { 
    [UIView animateWithDuration:2.0 
        animations:^{ 
         self.view.frame = resizeFrame; 
         } completion:(void (^)(BOOL)) ^{ 
       self.minimized = true; 

} 

看來,一旦創建與特定的框架,我不能改變它沒有別的。

你能告訴我如何使AVPlayer圖層與我的視圖控制器的視圖調整大小?

謝謝

回答

0

AVPlayerLayers不會自動調整其父視圖的大小。如果你要覆蓋一個UIView的layerClass與AVPlayerLayer,你應該也還覆蓋其layoutSublayersOfLayer方法,像這樣:

- (void)layoutSublayersOfLayer:(CALayer *)layer { 
    [super layoutSublayersOfLayer:layer]; 
    if (layer == self.layer) { 
     [self layer].frame = self.bounds; 
    } 
} 

而且在斯威夫特3:

class PlayerLayerDisplayer: UIView { 

    override class var layerClass: AnyClass { 
     get { 
      return AVPlayerLayer.self 
     } 
    } 

    override func layoutSublayers(of layer: CALayer) { 
     super.layoutSublayers(of: layer) 
     guard layer == self.layer else { 
      return 
     } 
     layer.frame = self.bounds 
    } 
} 
相關問題