【问题标题】:Swift scaleAspectFit only height of imageSwift scaleAspectFit仅图像的高度
【发布时间】:2017-03-01 04:34:23
【问题描述】:

我的 Swift 代码中有这个图像视图

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

【问题讨论】:

  • 假设高度大于宽度,scaleAspectFill 会这样做。
  • @dan scaleAspectFill 显示最后 300 像素,我怎样才能让它显示在前 300 像素?
  • 听起来你想要scaleAspectFit 而不是scaleAspectFill。您能否为您的问题添加一个视觉示例?

标签: ios swift


【解决方案1】:

你需要使用纵横比,使用已知宽度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

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 2022-12-29
    • 2019-11-01
    相关资源
    最近更新 更多