Swift - 纵向视频的帧尺寸

Swift -Frame dimensions for portrait video

如果我想在单元格内显示 16:9 水平视频,我使用尺寸:

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)

这将给我一个水平单元格:

如果视频是 16:9 就没问题,但如果用户以纵向录制视频,则视频缩略图位于视图中间且有黑边。

在这种情况下,当它是纵向视频时,我想调整单元格以使其支持纵向视频,以提供类似于所有社交网络当前用于纵向的内容(我只需要 1单元格,这只是一个纵向单元格示例的屏幕截图):

我知道如何设置单元格,但我不知道纵向视频使用什么尺寸:

例如我发现 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)

纵向视频的尺寸是多少?

使用这个 blog post that said the iPhone vertical aspect ratio (the dimensions for a portrait video) is 9:16 and this 我为 2 列做了这个:

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)
}