【问题标题】:Try to change the frame of UIImageView but it doesn't work according to the code尝试更改 UIImageView 的框架,但根据代码它不起作用
【发布时间】:2021-06-03 04:37:03
【问题描述】:

我做了一个 UIImageView 的子类。我使用它的函数setupView() 在 vi​​ewDidLoad() 中设置每个 DirectionView 对象的框架,它工作得很好。但是当我在触发按钮时使用相同的函数重置 DirectionView 对象的框架时,新的框架值不是我所期望的。

调试区显示的x、y、width和height值都是正确的。但是,我使用print("Original frame: \(self.frame)") 打印出来的帧值显示了一组不同的值。

为什么会这样?以及如何解决?

class DirectionView: UIImageView {
    
    override init(image: UIImage?) {
        super.init(image: image)

    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)

    }
    
    func setupView(_ degree: Double, showSigInfo: Bool) {
        
        let rotationAngle = degree.toRadians
        var height: Double = 375 / 2
            
        let width = height / 47 * 37
        let x = 375 / 2  - width / 2
        let y = 0.0
        self.frame = CGRect(x: x, y: y, width: width, height: height)

        print("Original frame: \(self.frame)")
        self.contentMode = .scaleAspectFit
        self.setAnchorPoint(CGPoint(x: 0.5, y: 1.0))
        
        UIView.animate(withDuration: 0.0) {
            self.transform = CGAffineTransform(rotationAngle: rotationAngle)
        }

    }
}

【问题讨论】:

  • 在设置框架之前添加这一行:self.translatesAutoresizingMaskIntoConstraints = true
  • 嗨@RajaKishan,感谢您的建议,但这不会改变结果。

标签: ios swift uiimageview resize


【解决方案1】:

问题是由anchor point 引起的。根据文档,“对视图的所有几何操作都发生在指定点附近”(指锚点)。当你旋转图像,然后调整它的大小时,锚点位置不好,所以最终的高度和宽度不是你指定的。

我避免进行所有会导致锚点正确位置(或正确高度和宽度)的几何计算。但是,这里有一个解决方案:

  1. 删除代码行self.setAnchorPoint(CGPoint(x: 0.5, y: 1.0))
  2. 在设置框架之前,即在self.frame = CGRect(x: x, y: y, width: width, height: height) 行之前。添加以下行:UIView.animate(withDuration: 0.0) {self.transform = CGAffineTransform(rotationAngle: 0)}

这应该做的工作。

为什么有效?锚点的默认值为 (0.5,0.5),当图像位于其标准位置(旋转 = 0)时,它会提供正确的大小调整。因此,解决方案将图像旋转到其标准位置,调整大小,然后将其旋转到您想要的角度。设备的速度足够快,以至于用户不会注意到双旋转。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    相关资源
    最近更新 更多