OGeek|极客世界-中国程序员成长平台

标题: ios - 当图像由于内容模式而缩小时,使 ImageView 调整其高度以匹配其图像的高度 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 14:11
标题: ios - 当图像由于内容模式而缩小时,使 ImageView 调整其高度以匹配其图像的高度

我有一个 ImageView ,它的左、右和上边缘被固定到它的 super View ,它的下边缘与下面的标签有一个固定的间距。它没有任何宽度或高度限制,因此它应该从其图像的固有尺寸中获取其高度。内容模式设置为Aspect Fit

如果图像的宽度小于或等于 ImageView 的宽度(情况 1 和 2,请参见下图),则此方法非常有用。但是,如果图像的宽度超过其包含的 ImageView 的宽度,我会遇到问题(案例 3):

图像按预期缩小,使其宽度与 ImageView 的宽度相匹配。 但 ImageView 不会相应地更新其高度,会在上方和下方留下空白。我知道 ImageView 仍然从图像的 original 高度获得它的高度。但是由于内容模式,图像的高度现在要小很多,我希望 ImageView 调整其高度以匹配图像的实际高度。

我正在寻找一种适用于这三种情况的简洁解决方案,最好是一种适用于 IB_DESIGNABLE View 的解决方案。有什么想法吗?

案例一

内在宽度<框架宽度

intrinsic width < frame width

案例 2

内在宽度 = 框架宽度

intrinsic width = frame width

案例 3

内在宽度 > 框架宽度

intrinsic width > frame width



Best Answer-推荐答案


您可以通过以下方式在 UIImageView 上创建扩展:

extension UIImageView {
    @IBInspectable var shouldAdjustHeight: Bool {
        get {
            return self.frame.size.height == self.adjustedHeight;
        }
        set {
            if newValue {
                if !shouldAdjustHeight {
                    let newHeight = self.adjustedHeight

                    // add constraint to adjust height
                    self.addConstraint(NSLayoutConstraint(
                        item:self, attribute:NSLayoutAttribute.Height,
                    relatedBy:NSLayoutRelation.Equal,
                    toItem:nil, attribute:NSLayoutAttribute.NotAnAttribute,
                    multiplier:0, constant:newHeight))
            }
        }
        else {
            let newHeight = self.adjustedHeight
            // create predicate to find the height constraint that we added
            let predicate = NSPredicate(format: "%K == %d && %K == %f", "firstAttribute", NSLayoutAttribute.Height.rawValue, "constant", newHeight)
            // remove constraint
            self.removeConstraints(self.constraints.filter{ predicate.evaluateWithObject($0) })
        }
    }
}

var adjustedHeight: CGFloat {
    let screenWidth = UIScreen.mainScreen().bounds.width
    let deviceScaleFactor = screenWidth/self.bounds.size.width
    return CGFloat(ceilf(Float(deviceScaleFactor * AVMakeRectWithAspectRatioInsideRect((self.image?.size)!, self.bounds).size.height))) // deviceScaleFactor multiplied with the image size for the frame
    // I am using size class in my XIB with value as (Any,Any) and I was not getting correct frame values for a particular device so I have used deviceScaleFactor.
    // You can modify above code to calculate newHeight as per your requirement
}
}

添加上述扩展后,您可以在Interface-builder中设置属性,如下所示。

enter image description here

在设置此属性时,高度约束将被添加到您的 imageViewadjustedHeight 的计算在我的解决方案中可能不是很整洁,所以您可以进一步研究。

关于ios - 当图像由于内容模式而缩小时,使 ImageView 调整其高度以匹配其图像的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35312935/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4