【问题标题】:Resizing UIImage to fit table cell ImageView调整 UIImage 的大小以适合表格单元格 ImageView
【发布时间】:2017-04-10 08:32:00
【问题描述】:

我有大小为 176 点乘 176 点的图像。我正在尝试调整它们的大小,以便它们适合 tableViewCell 的 ImageView。我遇到了一些问题。

问题

  • 我不知道 tableViewCell 中图像视图的实际大小。
  • 如果我只是简单地添加图像而不调整它的大小,它会非常锐利以至于失去细节:
  • 如果我在 UIImage 上使用这个扩展(如下),那么 UIImage 的透明部分会变成黑色,而不是我想要的:

extension UIImage {
    func resizeImageWithBounds(bounds: CGSize) -> UIImage {
        let horizontalRatio = bounds.width/size.width
        let verticalRatio = bounds.height/size.height
        let ratio = max(horizontalRatio, verticalRatio)
        let newSize = CGSize(width: size.width * ratio, height: size.height * ratio)
        UIGraphicsBeginImageContextWithOptions(newSize, true, 0)
        draw(in: CGRect(origin: CGPoint.zero, size: newSize))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
}

我正在寻找有关 UIImageView 有多大以及如何最好地将图像调整到其中的信息。我真的不想创建另一组资产(我有很多图像),我认为我不应该这样做。

【问题讨论】:

  • 我知道这是个很愚蠢的问题,但你检查过 UIImageView.contentMode 设置了吗?
  • 不,我没有。那是什么?
  • 哦,等等,我有,但我认为这对我的问题没有帮助,不是吗?

标签: ios swift xcode uiimageview uiimage


【解决方案1】:

尝试更改单元格的contentMode

cell.imageView?.contentMode = .scaleAspectFit

或者,如果这不起作用,以下是解决调整后图像变黑问题的方法:

UIGraphicsBeginImageContextWithOptions(newSize, false, 0) // <-- changed opaque setting from true to false

【讨论】:

  • contentMode 没问题,但你的第二个 sn-p 工作正常。
猜你喜欢
  • 2014-06-10
  • 2017-03-12
  • 2011-07-07
  • 2010-10-27
  • 1970-01-01
  • 1970-01-01
  • 2019-06-21
  • 2019-05-08
  • 1970-01-01
相关资源
最近更新 更多