【问题标题】:How to calculate image dimensions after scaling?缩放后如何计算图像尺寸?
【发布时间】:2017-01-17 09:48:51
【问题描述】:

我正在尝试创建具有动态大小的表格单元格,特别是高度。单元格包含 4 行文本和图像视图。图像视图中的图像通常具有较大的分辨率,因此应将其缩放以适应图像视图。我使用 aspectFit 模式在图像视图中进行缩放。

如果我硬编码单元格高度,图像视图会收到额外的空间(用颜色突出显示)

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
    return 500
}

要删除额外的填充,我需要在缩放后计算图像尺寸。 我如何在 Swift 中做到这一点?

我也尝试了 UITableViewAutomaticDimension,但单元格大小变得很大(取决于图像分辨率),因为单元格尺寸是根据全分辨率图像计算的,而不是按比例缩放的(使用 aspectFit 模式)

this answer 中提供了另一种解决方案,但该解决方案的性能非常差,无法用于表格视图。我相信有更好的解决方案,因为图像已经被系统缩放以适应宽度,我只需要知道缩放图像的尺寸。

【问题讨论】:

    标签: ios swift uitableview autolayout ios-autolayout


    【解决方案1】:

    发布问题后,我想到了新的想法。如果缩放模式始终为 aspectFit 并且单元格宽度始终相同,那么知道我可以计算缩放因子。之后可以计算单元格高度:

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        // current cell height = 4 text lines + scaled image
    
        // Number of text lines
        let numberOfTextLines: CGFloat = 4.0
        // Line height of font used in text labels
        let textLineHeight = UIFont.systemFont(ofSize: 17).lineHeight
        // Size of image to show in cell
        let imageSize = imageRecords[indexPath.row].image!.size
        // Scale factor: cell width to image width
        let scale = self.tableView.bounds.width / imageSize.width
    
        // Cell height = sum of all lines height + scaled image height
        return (numberOfTextLines * textLineHeight) + (scale * imageSize.height)
    }
    

    为提高单元格高度精度,应考虑单元格边距。

    【讨论】:

      【解决方案2】:

      如果约束设置正确,UITableViewAutomaticDimension 会得到你想要的。仅屏幕截图就很难(分享故事板/xib 有帮助!),但您可能希望根据我所看到的执行以下操作:

      • 移除图像视图的底部约束
      • 添加一个约束内容视图的底部图像视图的底部
      • 使用 UITableViewAutomaticDimension

      在某些情况下使用自动尺寸时性能仍然很差,但请试一试。

      【讨论】:

      • 不幸的是,从内容视图底部到图像视图底部的约束在 UITableViewAutomaticDimension 上给出了相同的行高,反之亦然约束。填充大小与以前保持一致。
      猜你喜欢
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 2018-01-02
      相关资源
      最近更新 更多