AvPlayerLayer没有正确调整大小?

时间:2014-08-13 01:15:28

标签: ios iphone uiview avplayer

我有一个带有UIImageView的旋转木马对象,我试图subLayer AvPlayerLayer。

尽管它没有填满_videoView的全部边界,它看起来高度较小,虽然我已经测试过将高度更改为极值但它仍然保持在那个大小,只要它重叠了的UIImageView。

我用来实现此目的的代码如下:

    UIView *embeddedView = [[UIView alloc] initWithFrame:_videoView.bounds];
embeddedView.center = CGPointMake(100, 140);
AVPlayerItem *avPlayeritem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:[_videoURLS objectAtIndex:carousel.currentItemIndex]]];
AVPlayer *avPlayer = [[AVPlayer alloc] initWithPlayerItem:avPlayeritem];
AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
[avPlayerLayer setFrame:embeddedView.frame];
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
[avPlayerLayer setNeedsLayout];
[embeddedView.layer addSublayer:avPlayerLayer];
[carousel.currentItemView addSubview:embeddedView];
//Assign to notication to check for end of playback
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:avPlayeritem];
[avPlayer seekToTime:kCMTimeZero];
[avPlayer play];

这是一个正在发生什么的图像,因为你可以在顶部和底部分辨它: viewOffBounds

造成这种情况的原因是什么?如何解决这个问题?

2 个答案:

答案 0 :(得分:5)

我认为视频没有填满videoView的全部界限,因为你设置了avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspect。 你应该将它设置为AVLayerVideoGravityResizeAspectFill,并且il就可以了。 区别在于:

  • AVLayerVideoGravityResizeAspect显示与原始大小成比例的视频,并且不允许任何变形。

  • AVLayerVideoGravityResizeAspectFill,调整视频大小,填充其子视图的完整范围,不关心比例。

还有一件事,让[avPlayerLayer setFrame:embeddedView.bounds]比[avPlayerLayer setFrame:embeddedView.frame]更好;

希望这会有所帮助:)

答案 1 :(得分:0)

可接受的答案不能解决重复的,重叠的层的问题。而是不要尝试addSublayer并创建AVPlayer支持的视图:

迅速

import UIKit
import AVFoundation

/// A simple `UIView` subclass that is backed by an `AVPlayerLayer` layer.
class PlayerView: UIView {
    var player: AVPlayer? {
        get {
            return playerLayer.player
        }

        set {
            playerLayer.player = newValue
        }
    }

    var playerLayer: AVPlayerLayer {
        return layer as! AVPlayerLayer
    }

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

Objective-C

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface PlayerView : UIView
@property (nonatomic) AVPlayer *player;
@end

@implementation PlayerView
+ (Class)layerClass {
    return [AVPlayerLayer class];
}
- (AVPlayer*)player {
    return [(AVPlayerLayer *)[self layer] player];
}
- (void)setPlayer:(AVPlayer *)player {
    [(AVPlayerLayer *)[self layer] setPlayer:player];
}
@end

这样,图层将随视图正确调整大小。

参考文献:

  1. Swift sample code from Apple
  2. AVFoundation Programming Guide