在UIScrollView中调整AVPlayer的大小

问题描述 投票:3回答:1

我有一个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倍)。我在做什么错?

ios swift uiscrollview
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.