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