ios - 缩放后如何计算图像尺寸?

标签 ios swift uitableview autolayout ios-autolayout

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

Cell layout

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

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

Horizontal image

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

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

this answer 中提供了另一种解决方案, 但此解决方案的性能非常差,对于 TableView 来说是 Not Acceptable 。我相信有更好的解决方案,因为图像已经被系统缩放以适应宽度,我只需要知道缩放图像的尺寸。

最佳答案

发布问题后,我想到了新的想法。如果缩放模式始终是 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)
}

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

关于ios - 缩放后如何计算图像尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41693824/

相关文章:

ios - 判断 UIView 数组中的 UIView 是否完全重叠,然后调整位置

ios - 如何通过DiffableDataSource更新Section中的页脚而不会造成闪烁效果?

ios - Swift:将普通字符串转换为 YYYY-MM-DD 类型的字符串?

swift - 自定义 UITableViewCell 中的 UIImageView 在单击时调整大小

iphone - 使用 "tableView:sectionForSectionIndexTitle:atIndex:"帮助滚动到 TableViewHeader?

ios - 如何在 Interface Builder 中编辑表格 View 单元格的文本?

ios - CMPedometerData 中的结束日期不正确

ios - [[UIApplication sharedApplication] currentUserNotificationSettings].types 的调用总是返回 UIUserNotificationTypeNone

ios - 什么相当于 iOS UIImageView 的 Android ImageView 的中心裁剪比例类型?

swift - 如何在Xcode断开连接的设备上检查错误?