【发布时间】:2020-05-12 10:58:30
【问题描述】:
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
【问题讨论】:
-
问题在于算术。要在保持长宽比不变的情况下缩放矩形,您必须将其高度和宽度乘以(或除)相同的数字。
-
@matt 我应该把它除以多少?
-
任何你喜欢的号码。