0

1080p 高清视频的纵横比为 16:9,并为单元格中的视频设置帧,以便将其完全填满,我会使用 view.frame.width * 9 / 16

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    // the collection view is pinned to both sides of the vc with no spacing
    let width = collectionView.frame.width

    let videoHeight: CGFloat = width * 9 / 16

    return CGSize(width: width, height: videoHeight)
}

// inside the cell itself:

let videoHeight: CGFloat = self.frame.width * 9 / 16

contentView.addSubview(thumbnailImageView)
thumbnailImageView.topAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
thumbnailImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
thumbnailImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true

// here is where I set the thumbnail's height
thumbnailImageView.heightAnchor.constraint(equalToConstant: videoHeight).isActive = true

这完美地给了我:

在此处输入图像描述

问题是我想要一个类似于 youtube 的较小版本的 thumbnailImageView。我想在屏幕左侧添加较小的 thumbnailImageView 但保持纵横比相同

在此处输入图像描述

问题是当我尝试这样做时,我得到了一个正方形而不是一个矩形。我将单元格的宽度除以 3,然后将其乘以 9 /16,但这不起作用。我之所以使用(width / 3)它是因为我虽然它会保持纵横比不变,但会减小 thumbnailImageView 的大小,但它不起作用。

在此处输入图像描述

我哪里错了?

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    // the collection view is pinned to both sides of the vc with no spacing
    let width = collectionView.frame.width

    let videoHeight: CGFloat = (width / 3) * 9 / 16

    return CGSize(width: width, height: videoHeight)
}

// inside the cell itself
let videoHeight = (self.frame.width / 3) * 9 / 16

contentView.addSubview(thumbnailImageView)
thumbnailImageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8).isActive = true
thumbnailImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8).isActive = true

// here is where I set the thumbnail's height and width
thumbnailImageView.heightAnchor.constraint(equalToConstant: videoHeight).isActive = true
thumbnailImageView.widthAnchor.constraint(equalToConstant: videoHeight).isActive = true
4

1 回答 1

3

您可以使用 AVMakeRect(aspectRatio:insideRect:) 函数来获取一个缩放的矩形,该矩形在边界矩形内保持指定的纵横比。

您可以在此处参考 API 。

通过使用上述 API,您的 videoHeight 值将填充如下。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // the collection view is pinned to both sides of the vc with no spacing
    let width = collectionView.frame.width
    let rect = AVMakeRect(aspectRatio: CGSize(width: 16, height: 9), insideRect: CGRect(origin: .zero, size: CGSize(width: width / 3, height: CGFloat.infinity)))
    let videoHeight: CGFloat = rect.size.height
    return CGSize(width: width, height: videoHeight)
}

在单元格中,您可以简单地具有如下高度。

let videoHeight = self.frame.height
于 2020-05-12T11:03:47.057 回答