简体   繁体   English

调整UIImage的大小以适合表格单元格ImageView

[英]Resizing UIImage to fit table cell ImageView

I have images of the size 176 points by 176 points. 我的图像尺寸为176点乘176点。 I am trying to resize them so that they fit into a tableViewCell's ImageView. 我正在尝试调整它们的大小,以使它们适合tableViewCell的ImageView。 There are a few problems that I am coming across. 我遇到了一些问题。

Problems 问题

  • I don't know what size the image view in the tableViewCell actually is. 我不知道tableViewCell中的图像视图实际大小。
  • If I simply add the image without resizing it, it is so sharp that it looses detail: 如果我只是添加图像而不调整其大小,那么它会变得太清晰以至于失去细节: 清晰的影像
  • If I use this extension on UIImage (below), then the transparent parts of the UIImage turn to black, not what I want: 如果我在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!
    }
}

I am looking for information on how big the UIImageView is and how to best resize an image into it. 我正在寻找有关UIImageView的大小以及如何最佳地将图像调整到其中的信息。 I really don't want to create another set of assets (I have a lot of images), and I don't think I should have to. 我真的不想创建另一组资产(我有很多图像),我也不认为必须这样做。

Try changing the contentMode of the cell. 尝试更改单元格的contentMode

cell.imageView?.contentMode = .scaleAspectFit

Or, if that doesn't work, here's how to fix the issues of your resized images turning black: 或者,如果这样不起作用,请按照以下方法解决调整大小后的图像变黑的问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM