在UIScrollView中调整AVPlayer的大小

时间:2016-11-01 17:27:27

标签: ios swift uiscrollview

我有一个AVPlayerViewController,其AVPlayer视图已添加为UIView的子视图。此UIView已添加到UIScrollView。我们的想法是实现一个"移动和扩展"观看视频。当UIScrollView中的视图为UIImageView时,我可以使用它。但是,如果视图是带有UIView子视图的AVPlayer,则UIView的比例似乎太小。

这是我的代码:

override func viewDidLoad() {
    super.viewDidLoad()

    videoPlayerController = VideoPlayerController()
    videoPlayerController.videoURL = url
    self.addChildViewController(videoPlayerController)
    videoView.addSubview(videoPlayerController.view)

    videoPlayerController.view.translatesAutoresizingMaskIntoConstraints = false

    let left = NSLayoutConstraint(item: videoPlayerController.view, attribute: .left, relatedBy: .equal, toItem: videoView, attribute: .left, multiplier: 1, constant: 0)
    let right = NSLayoutConstraint(item: videoPlayerController.view, attribute: .right, relatedBy: .equal, toItem: videoView, attribute: .right, multiplier: 1, constant: 0)
    let top = NSLayoutConstraint(item: videoPlayerController.view, attribute: .top, relatedBy: .equal, toItem: videoView, attribute: .top, multiplier: 1, constant: 0)
    let bottom = NSLayoutConstraint(item: videoPlayerController.view, attribute: .bottom, relatedBy: .equal, toItem: videoView, attribute: .bottom, multiplier: 1, constant: 0)

    videoView.addConstraints([left, right, top, bottom])

    let asset = AVAsset(url: url)
    let clipVideoTrack = asset.tracks(withMediaType: AVMediaTypeVideo).first!
    videoView.frame = CGRect(x: 0, y: 0, width: clipVideoTrack.naturalSize.height, height: clipVideoTrack.naturalSize.width)
    setZoomScale()
}

fileprivate func setZoomScale() {
    let widthScale = scrollView.bounds.size.width / videoView.bounds.size.width

    scrollView.minimumZoomScale = widthScale
    scrollView.zoomScale = widthScale
}

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return videoView
}

func scrollViewDidZoom(_ scrollView: UIScrollView) {
    let videoViewSize = videoView.frame.size
    let scrollViewSize = scrollView.bounds.size

    let verticalPadding = videoViewSize.height < scrollViewSize.height ? (scrollViewSize.height - videoViewSize.height) / 2 : 0
    let horizontalPadding = videoViewSize.width < scrollViewSize.width ? (scrollViewSize.width - videoViewSize.width) / 2 : 0
    }

    scrollView.contentInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding)
}

应该发生的是videoView应该填满屏幕的宽度并居中,并能够放大它的自然尺寸。相反,视图在屏幕上显示为居中但更小(可能小3倍)。我做错了什么?

1 个答案:

答案 0 :(得分:0)

Swift5

请尝试一下,它将为您提供所需的视频大小。

    let offsetX = max((scrollView.bounds.width - scrollView.contentSize.width) * 0.5, 0)
            let offsetY = max((scrollView.bounds.height - scrollView.contentSize.height) * 0.5, 0)
            scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)