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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM