【问题标题】:UIImageView resizing to eliminate blank space IOSUIImageView调整大小以消除空白IOS
【发布时间】:2019-03-09 20:07:04
【问题描述】:

我的UIImageView 处于宽高比匹配模式,这会在实际图像下方留下空白。

蓝色空间是我想要消除的,所以 imageView 包装了图像(如果我有包装内容)。似乎是一项简单的任务,但我很快意识到图像在方面适合,因此图像视图会改变图像的宽度和高度,但随后我必须根据更改后的图像对图像视图进行计算,这将产生不断缩小图像的循环。

我只是想删除空白以使其看起来更简洁。 GitHub 上的完整项目:https://github.com/sak6lab/Closet-Space

【问题讨论】:

  • 你想改变 width 以获得一致的 heights 吗?或者改变height以获得一致的widths
  • 对不起,我不太明白这个问题。
  • @DonMag 我想我想改变高度以获得一致的宽度,但是我已经计算出每个单元格的宽度量,这又与 UIImageView 相同。
  • 我想我只是想知道您打算如何布置并排元素,其中一个图像可能又高又窄(如 T 恤),而下一个图像可能又短又宽(比如鞋子)。如果您尝试调整图像大小以删除额外的空白空间,您可能会满意其中一个而不是另一个。 (虽然有点离题)

标签: ios swift uiimageview


【解决方案1】:

我最近为此提交了一份雷达,因为我认为这是不正常的行为。

目前,我发现解决此问题的最佳方法是根据图像的纵横比向图像视图添加纵横比约束。 (但是,当图像更改时,您必须更新约束)。

类似...

imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor, multiplier: image.size.width / image.size.height).isActive = true

也许你可以把它包装成一个UIImageView 子类。覆盖image 属性的didSet,甚至只是添加一个新函数。

但要小心,因为您需要确保只创建 一个 约束,并在随后的传递中更新已经存在的约束。

【讨论】:

  • 感谢它绝对有帮助!
【解决方案2】:

所以基于Fogmeister的回答,而不是宽度,将其更改为高度,然后将高度更改为视图的宽度

let newsize = self.feedImage.contentClippingRect

self.feedImage.heightAnchor.constraint(equalTo: self.feedImage.widthAnchor, multiplier:newsize.width / newsize.height).isActive = true

newsize 是我们使用 .scaleaspectfit 缩放后的 CGRect 请注意以下来自https://www.hackingwithswift.com/example-code/uikit/how-to-find-an-aspect-fit-images-size-inside-an-image-view的扩展名

extension UIImageView {
    var contentClippingRect: CGRect {
    guard let image = image else { return bounds }
    guard contentMode == .scaleAspectFit else { return bounds }
    guard image.size.width > 0 && image.size.height > 0 else { return bounds }

    let scale: CGFloat
    if image.size.width > image.size.height {
        scale = bounds.width / image.size.width
    } else {
        scale = bounds.height / image.size.height
    }

    let size = CGSize(width: image.size.width * scale, height: image.size.height * scale)
    let x = (bounds.width - size.width) / 2.0
    let y = (bounds.height - size.height) / 2.0
    //print ("image resizing[width=\(size.width), height=\(size.height)")
    return CGRect(x: x, y: y, width: size.width, height: size.height)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    相关资源
    最近更新 更多