ios - Swift scaleAspectFit 仅图像高度

标签 ios swift

我的 Swift 代码中有这个 ImageView

let background_image: UIImageView = {
    let im = #imageLiteral(resourceName: "backg")
    let view=UIImageView()
    view.contentMode = .scaleAspectFit
    view.image=im
    return view
}()

我的background_image的大小是300x300,但我不知道im的大小。我希望im的宽度始终是300,但我不想缩小高度,我只想显示适合UIImageView的300px

最佳答案

您需要使用宽高比,并使用已知的宽度 300,还需要将 UIImageView 内容模式设置为 aspectFit

此代码示例使用 SDWebImage 进行图像加载,但您可以使用任何其他

self.newsImageView.sd_setImage(with: URL as URL, placeholderImage: UIImage(named: "genericImageR"), options: SDWebImageOptions(), completed: { (image, error, type, url) in
            DispatchQueue.global().async {
                DispatchQueue.main.async {
                    if(image != nil)
                    {
                        //your downloaded image aspect ratio
                        let aspectRatio = (image! as UIImage).size.height/(image! as UIImage).size.width
                        self.newsImageView.image = image
                        if(self.imageWasLoaded != nil)
                        {
                            //your know width 300, but if you want you can use the width of your component
                            self.imageWasLoaded!(self.newsImageView.frame.size.width * aspectRatio)
                        }
                    }
                }
            }
        })

并使用 300*aspectRatio 的高度结果调整您的 UI

希望对你有帮助

关于ios - Swift scaleAspectFit 仅图像高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42516214/

相关文章:

ios - Swift vs Objective-C 斐波那契数列速度比较

ios - 混合 Storyboard中的单元和以编程方式创建的单元

ios - 在iOS中解析Google翻译JSON

ios - rangeOfUnit 在一个月中的几周返回 `NSNotFound`(iOS7 错误)

arrays - 使用下标扩展数组 (Swift)。 Xcode 6 beta 7 中的错误?

android - 将 Firebase 用于 iOS 和 Android 应用

ios - 删除 iOS 中的后台位置警报?

ios - NSThread参数问题

iphone - 将通用应用程序作为缩放的 iPhone 应用程序运行?

ios - 去除圆角 UITableViewCell