AVPlayerLayer 设置自动布局

如果要设置playerLayer的布局,目前iOS不支持layer设置AutoLayout也不支持autoresizingMask,所以无法给playerLayer设置约束,当然可以采用原始的方法,就是在viewDidLayoutSubviews中再次设置playerLayer的frame,但是这样在屏幕旋转时会有一片短暂的空白区域,虽然很快就消失了,但是这样效果不是很好。

解决方案: 通过UIView来处理,自定义一个UIView的子类,设置这个view的layerClass为AVPlayerLayer类型,然后直接使用这个子类的layer作为AVPlayerLayer,那么此时不需要设置playerLayer的frame,设置这个view的约束或frame即可

以下界面我是通过XIB搭建界面
#import "XYVideoPlayer.h"
#import 

@implementation XYVideoPlayer

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

@end

#import "ViewController.h"
#import 
#import "XYVideoPlayer.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet XYVideoPlayer *videoLayer;
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    self.videoLayer.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    self.asset = [AVAsset assetWithURL:videoURL];
    
    AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithAsset:self.asset];
    
    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    // 将player输出到显示动画层playerLayer
    self.playerLayer = (AVPlayerLayer *)self.videoLayer.layer;
    [self.playerLayer setPlayer:self.player];
}
AVPlayerLayer 设置自动布局_第1张图片
Snip20161114_7.png

你可能感兴趣的:(AVPlayerLayer 设置自动布局)