iOS在CGRect中播放电影

时间:2013-05-01 00:15:15

标签: ios mpmovieplayercontroller

我正在尝试在我的iOS应用中添加一个介绍视频。我希望视频在没有控件的情况下播放,并且在我为它创建的框中播放。但我不知道该怎么做。它也没有以正确的尺寸播放它是超小的。如果你看下面你会看到我的尝试,但它无法正常工作。我如何实现这一目标?

-(void)initVideo{
    MPMoviePlayerViewController *moviePlayerController=[[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"video" ofType:@"mp4"]]];

    UIView * contain = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    [contain addSubview:moviePlayerController.view];
    [self.view addSubview:contain];

    MPMoviePlayerController *player = [moviePlayerController moviePlayer];

    player.fullscreen = NO;
    [player play];
}

enter image description here

2 个答案:

答案 0 :(得分:1)

我实际上在我的书中有代码,告诉你如何做到这一点:

http://www.apeth.com/iOSBook/ch28.html#_mpmovieplayercontroller

读到第一个代码块。正如您所看到的,我们加载一部电影,决定我们想要显示它的视图中的矩形,并显示它:

NSURL* m = [[NSBundle mainBundle] URLForResource:@"ElMirage"
                                   withExtension:@"mp4"];
MPMoviePlayerController* mp =
    [[MPMoviePlayerController alloc] initWithContentURL:m];
self.mpc = mp; // retain policy
self.mpc.shouldAutoplay = NO;
[self.mpc prepareToPlay];
self.mpc.view.frame = CGRectMake(10, 10, 300, 250);
self.mpc.backgroundView.backgroundColor = [UIColor redColor];
[self.view addSubview:self.mpc.view];

当然你会想要改变这些价值观!但这就是技术。你也想要摆脱控制,但这很容易(在本章中进一步阅读)。

答案 1 :(得分:0)

由于您在视图中使用播放器,因此无需使用MPMoviePlayerViewController。请尝试以下代码:

-(void)initVideo{
    MPMoviePlayerController *moviePlayerController = [[MPMoviePlayerController alloc]initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"video" ofType:@"mp4"]]];

    UIView *contain = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    moviePlayerController.view.frame = contain.bounds;
    [contain addSubview:moviePlayerController.view];
    [self.view addSubview:contain];

    moviePlayerController.fullscreen = NO;
    [moviePlayerController play];
}

此外,如果您使用的是导航栏或状态栏,则应将其从高度移开:

CGRect f = [[UIScreen mainScreen] bounds];
f.size.height -= [[UIApplication sharedApplication] statusBarFrame].size.height + self.navigationController.navigationBar.frame.size.height;
UIView *contain = [[UIView alloc] initWithFrame:f];