【问题标题】:How to rotate UIVIew in its top left coordinates?如何在其左上角坐标中旋转 UIVIew?
【发布时间】:2018-01-02 11:46:03
【问题描述】:

现有的 CGAffineTransform 可以很好地完成这项工作,但它只在其中心点旋转。我想在其左上角坐标中旋转 UIView,

轮换代码:

// here rectangle is UIView
rectangle.transform = CGAffineTransform(rotationAngle: 90.degreesToRadians)

扩展:

// use to convert degree to radian
extension BinaryInteger {
    var degreesToRadians: CGFloat { return CGFloat(Int(self)) * .pi / 180 }
}

我在建议的问题中找不到我的答案。

【问题讨论】:

标签: ios swift uiview


【解决方案1】:

只需在转换之前更改图层的锚点。例如:

rectangle.layer.anchorPoint = CGPoint.zero
rectangle.transform = CGAffineTransform(rotationAngle: 90.degreesToRadians)

【讨论】:

    【解决方案2】:

    在这里感谢 Trix 和 the4kman 的想法。我解决了我的问题。在这里,Trix 的回答并没有完全帮助我。但他给出了一些暗示。使用这些提示我解决了我的答案。

    第一步

    为 UIView 创建这个扩展来设置锚点

    extension UIView{
        func setAnchorPoint(anchorPoint: CGPoint) {
    
            var newPoint = CGPoint(x: self.bounds.size.width * anchorPoint.x, y: self.bounds.size.height * anchorPoint.y)
            var oldPoint = CGPoint(x: self.bounds.size.width * self.layer.anchorPoint.x, y: self.bounds.size.height * self.layer.anchorPoint.y)
    
            newPoint = newPoint.applying(self.transform)
            oldPoint = oldPoint.applying(self.transform)
    
            var position : CGPoint = self.layer.position
    
            position.x -= oldPoint.x
            position.x += newPoint.x;
    
            position.y -= oldPoint.y;
            position.y += newPoint.y;
    
            self.layer.position = position;
            self.layer.anchorPoint = anchorPoint;
        }
    }
    

    用法

    rectangle.setAnchorPoint(anchorPoint: CGPoint.zero)
    rectangle.transform = CGAffineTransform(rotationAngle: 90.degreesToRadians)
    

    这很完美。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多