• AVPlayerLayer


    AVPlayerLayer

    最后一个图层类型是AVPlayerLayer。尽管它不是Core Animation框架的一部分(AV前缀看上去像),AVPlayerLayer是有别的框架(AVFoundation)提供的,它和Core Animation紧密地结合在一起,提供了一个CALayer子类来显示自定义的内容类型。

    AVPlayerLayer是用来在iOS上播放视频的。他是高级接口例如MPMoivePlayer的底层实现,提供了显示视频的底层控制。AVPlayerLayer的使用相当简单:你可以用+playerLayerWithPlayer:方法创建一个已经绑定了视频播放器的图层,或者你可以先创建一个图层,然后用player属性绑定一个AVPlayer实例。

    在我们开始之前,我们需要添加AVFoundation到我们的项目中。然后,清单6.15创建了一个简单的电影播放器,图6.16是代码运行结果。

    清单6.15 用AVPlayerLayer播放视频

     1 #import "ViewController.h"
     2 #import 
     3 #import 
     4 
     5 @interface ViewController ()
     6 
     7 @property (nonatomic, weak) IBOutlet UIView *containerView; @end
     8 
     9 @implementation ViewController
    10 
    11 - (void)viewDidLoad
    12 {
    13     [super viewDidLoad];
    14     //get video URL
    15     NSURL *URL = [[NSBundle mainBundle] URLForResource:@"Ship" withExtension:@"mp4"];
    16 
    17     //create player and player layer
    18     AVPlayer *player = [AVPlayer playerWithURL:URL];
    19     AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    20 
    21     //set player layer frame and attach it to our view
    22     playerLayer.frame = self.containerView.bounds;
    23     [self.containerView.layer addSublayer:playerLayer];
    24 
    25     //play the video
    26     [player play];
    27 }
    28 @end
    View Code

    图6.16 用AVPlayerLayer图层播放视频的截图

    我们用代码创建了一个AVPlayerLayer,但是我们仍然把它添加到了一个容器视图中,而不是直接在controller中的主视图上添加。这样其实是为了可以使用自动布局限制使得图层在最中间;否则,一旦设备被旋转了我们就要手动重新放置位置,因为Core Animation并不支持自动大小和自动布局(见第三章『图层几何学』)。

    当然,因为AVPlayerLayerCALayer的子类,它继承了父类的所有特性。我们并不会受限于要在一个矩形中播放视频;清单6.16演示了在3D,圆角,有色边框,蒙板,阴影等效果(见图6.17).

    清单6.16 给视频增加变换,边框和圆角

     1 - (void)viewDidLoad
     2 {
     3     ...
     4     //set player layer frame and attach it to our view
     5     playerLayer.frame = self.containerView.bounds;
     6     [self.containerView.layer addSublayer:playerLayer];
     7 
     8     //transform layer
     9     CATransform3D transform = CATransform3DIdentity;
    10     transform.m34 = -1.0 / 500.0;
    11     transform = CATransform3DRotate(transform, M_PI_4, 1, 1, 0);
    12     playerLayer.transform = transform;
    13 14     //add rounded corners and border
    15     playerLayer.masksToBounds = YES;
    16     playerLayer.cornerRadius = 20.0;
    17     playerLayer.borderColor = [UIColor redColor].CGColor;
    18     playerLayer.borderWidth = 5.0;
    19 
    20     //play the video
    21     [player play];
    22 }
    View Code

  • 相关阅读:
    iOS 验证码按钮倒计时
    简单三层复习
    文件读写,改进版
    第一个文件读写的例子
    文件读写原理
    Ajax原理
    MVC,布局页面
    在MVC视图的代码块中,直接输出文本,有几种方式?
    MVC,如何在视图中声明方法,调用方法?
    MVC怎么在当前视图中,传递参数给到另外一个视图?
  • 原文地址:https://www.cnblogs.com/EchoHG/p/7624710.html
Copyright © 2020-2023  润新知