代码之家  ›  专栏  ›  技术社区  ›  Stefan

在集合视图单元格中自调整图像大小

  •  0
  • Stefan  · 技术社区  · 6 年前

    我想将照片添加到我的收藏视图单元格中,类似于snapchat如何。。。

    enter image description here

    1. 照片的数量会有所不同,因此整个单元格的高度也必须有所不同。

    2. 每张照片都应该保持它的高宽比。

    我最初的想法是要显示的图像数组,在单元格出列之前,计算每个单元格的大小,保持其纵横比,然后使用这些数据在单元格内部的集合视图中显示图像。然而,我的结果是缺乏的。

    enter image description here enter image description here

    这是计算尺寸的方法。

    func calculateImageSize(images: [UIImage], bounds: CGRect) -> [CGSize] {
    
        var imageSizes: [CGSize] = []
    
        var imageWidth: Int!
        var imageHeight: Int!
        var aspectRatio: CGSize!
        var convertedRect: CGRect!
    
        for i in 0..<images.count {
    
            imageWidth = images[i].cgImage?.width
            imageHeight = images[i].cgImage?.height
    
            aspectRatio = CGSize(width: imageWidth, height: imageHeight)
            convertedRect = AVMakeRect(aspectRatio: aspectRatio, insideRect: bounds)
    
            imageSizes.append(CGSize(width: convertedRect.width, height: convertedRect.height))
        }
    return imageSizes
    }
    

    有什么建议吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   drekka    6 年前

    我不认为这和图像大小有关。这是你需要定制的布局。我快速搜索了一下,找到了一个可能有帮助的库: https://github.com/rubygarage/collection-view-layouts