If I want to display a 16:9 horizontal video inside a cell I use the dimensions:
let videoHeight = self.frame.size.width * 9 / 16
contentView.addSubview(thumbnailImageView)
thumbnailImageView.heightAnchor.constraint(equalToConstant: videoHeight).isActive = true
thumbnailImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
thumbnailImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
// In the cv's sizeForItem I set the same height
let width = collectionView.frame.width
let videoHeight: CGFloat = width * 9 / 16
return CGSize(width: width, height: videoHeight)
which will give me a horizontal cell:
That work's fine if the video is in a 16:9 but if the user recorded the video in portrait the video thumbnail is in the middle of the view with the black sides.
In a situation like this, when it's a portrait video, I want to adjust the cell so that it supports a portrait video to give me something like what all the social networks are currently using for portrait (I only need 1 cell, this is just a screenshot of a example of a portrait cell):
I know how to set up the cell but I don't know what dimensions to use for a portrait video:
For example I find out if the video is portrait:
guard let videoTrack = AVAsset(url: videoUrl).tracks(withMediaType: AVMediaType.video).first else { return }
let transformedVideoSize = videoTrack.naturalSize.applying(videoTrack.preferredTransform)
let videoIsPortrait = abs(transformedVideoSize.width) < abs(transformedVideoSize.height)
var videoHeight = self.frame.size.width * 9 / 16 // dimension for horizontal video
if videoIsPortrait {
videoHeight = // dimension for portrait video ???
videoWidth = // not sure if this is necessary
}
thumbnailImageView.heightAnchor.constraint(equalToConstant: videoHeight).isActive = true
thumbnailImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
// if a width is necessary I set it otherwise I just use the trailing anchor
// I do the same thing inside sizeForItem to adjust to the portrait height (and width if necessary)
What are the dimensions for a portrait video?
Using this blog post that said the iPhone vertical aspect ratio (the dimensions for a portrait video) is 9:16
and this answer I did this for 2 columns:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let widthForTwoColumnCells = collectionView.frame.width / 2
let insideRect = CGRect(x: 0, y: 0, width: widthForTwoColumnCells, height: .infinity)
let rect = AVMakeRect(aspectRatio: CGSize(width: 9, height: 16), insideRect: insideRect)
let videoHeight: CGFloat = rect.size.height
return CGSize(width: widthForTwoColumnCells, height: videoHeight)
}