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